"use strict";
const os_1 = require("os");
class CocoaPodsService {
    constructor($fs) {
        this.$fs = $fs;
    }
    getPodfileHeader(targetName) {
        return `use_frameworks!${os_1.EOL}${os_1.EOL}target "${targetName}" do${os_1.EOL}`;
    }
    getPodfileFooter() {
        return `${os_1.EOL}end`;
    }
    mergePodfileHookContent(hookName, pathToPodfile) {
        return (() => {
            if (!this.$fs.exists(pathToPodfile).wait()) {
                throw new Error(`The Podfile ${pathToPodfile} does not exist.`);
            }
            let podfileContent = this.$fs.readText(pathToPodfile).wait();
            let hookStart = `${hookName} do`;
            let hookDefinitionRegExp = new RegExp(`${hookStart} *(\\|(\\w+)\\|)?`, "g");
            let newFunctionNameIndex = 1;
            let newFunctions = [];
            let replacedContent = podfileContent.replace(hookDefinitionRegExp, (substring, firstGroup, secondGroup, index) => {
                let newFunctionName = `${hookName}${newFunctionNameIndex++}`;
                let newDefinition = `def ${newFunctionName}`;
                let rubyFunction = { functionName: newFunctionName };
                if (firstGroup && secondGroup) {
                    newDefinition = `${newDefinition} (${secondGroup})`;
                    rubyFunction.functionParameters = secondGroup;
                }
                newFunctions.push(rubyFunction);
                return newDefinition;
            });
            if (newFunctions.length > 1) {
                let blokParameterName = "installer";
                let mergedHookContent = `${hookStart} |${blokParameterName}|${os_1.EOL}`;
                _.each(newFunctions, (rubyFunction) => {
                    let functionExecution = rubyFunction.functionName;
                    if (rubyFunction.functionParameters && rubyFunction.functionParameters.length) {
                        functionExecution = `${functionExecution} ${blokParameterName}`;
                    }
                    mergedHookContent = `${mergedHookContent}  ${functionExecution}${os_1.EOL}`;
                });
                mergedHookContent = `${mergedHookContent}end`;
                let newPodfileContent = `${replacedContent}${os_1.EOL}${mergedHookContent}`;
                this.$fs.writeFile(pathToPodfile, newPodfileContent).wait();
            }
        }).future()();
    }
}
exports.CocoaPodsService = CocoaPodsService;
$injector.register("cocoapodsService", CocoaPodsService);
