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