"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateIOSPackageJSON = exports.writePluginJSON = exports.findPluginClasses = exports.getPluginFiles = void 0;
const fs_extra_1 = require("fs-extra");
const path_1 = require("path");
const cordova_1 = require("../cordova");
const plugin_1 = require("../plugin");
const fs_1 = require("./fs");
async function getPluginFiles(plugins) {
    var _a;
    let filenameList = [];
    const options = {
        filter: (item) => {
            if (item.stats.isFile() && (item.path.endsWith('.swift') || item.path.endsWith('.m'))) {
                return true;
            }
            else {
                return false;
            }
        },
    };
    for (const plugin of plugins) {
        if (plugin.ios && (0, plugin_1.getPluginType)(plugin, 'ios') === 0 /* PluginType.Core */) {
            const pluginPath = (0, path_1.resolve)(plugin.rootPath, (_a = plugin.ios) === null || _a === void 0 ? void 0 : _a.path);
            const filenames = await (0, fs_1.readdirp)(pluginPath, options);
            filenameList = filenameList.concat(filenames);
        }
    }
    return filenameList;
}
exports.getPluginFiles = getPluginFiles;
async function findPluginClasses(files) {
    const classList = [];
    for (const file of files) {
        const fileData = (0, fs_extra_1.readFileSync)(file, 'utf-8');
        const swiftPluginRegex = RegExp(/@objc\(([A-Za-z0-9_-]+)\)/);
        const objcPluginRegex = RegExp(/CAP_PLUGIN\(([A-Za-z0-9_-]+)/);
        const swiftMatches = swiftPluginRegex.exec(fileData);
        if ((swiftMatches === null || swiftMatches === void 0 ? void 0 : swiftMatches[1]) && !classList.includes(swiftMatches[1])) {
            classList.push(swiftMatches[1]);
        }
        const objcMatches = objcPluginRegex.exec(fileData);
        if ((objcMatches === null || objcMatches === void 0 ? void 0 : objcMatches[1]) && !classList.includes(objcMatches[1])) {
            classList.push(objcMatches[1]);
        }
    }
    return classList;
}
exports.findPluginClasses = findPluginClasses;
async function writePluginJSON(config, classList) {
    const capJSONFile = (0, path_1.resolve)(config.ios.nativeTargetDirAbs, 'capacitor.config.json');
    const capJSON = (0, fs_extra_1.readJSONSync)(capJSONFile);
    capJSON['packageClassList'] = classList;
    (0, fs_extra_1.writeJSONSync)(capJSONFile, capJSON, { spaces: '\t' });
}
exports.writePluginJSON = writePluginJSON;
async function generateIOSPackageJSON(config, plugins) {
    const fileList = await getPluginFiles(plugins);
    const classList = await findPluginClasses(fileList);
    const cordovaPlugins = await (0, cordova_1.getCordovaPlugins)(config, 'ios');
    if (cordovaPlugins.length > 0) {
        classList.push('CDVPlugin');
    }
    writePluginJSON(config, classList);
}
exports.generateIOSPackageJSON = generateIOSPackageJSON;
