"use strict";
/** @format */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Parse = void 0;
var fs = __importStar(require("fs"));
var path = __importStar(require("path"));
var js_yaml_1 = __importDefault(require("js-yaml"));
var version_1 = require("./version");
var error_1 = require("../error");
var COMMON_VARIABLE_TYPE_REG = new RegExp(/\$\{(.*)\}/, 'i');
var SPECIALL_VARIABLE_TYPE_REG = new RegExp(/(.*)\((.*)\)/, 'i');
var OTHER_BASIC_DATA_TYPE = ['[object Number]', '[object Boolean]'];
var Parse = /** @class */ (function () {
    function Parse(path) {
        this.path = path;
        this.parsedObj = {};
        this.dependenciesMap = {};
        this.globalJsonKeyMap = {};
        this.globalKeyArr = [];
        this.magicVariablesArray = [];
        if (fs.existsSync(path)) {
            try {
                this.init(path);
            }
            catch (ex) {
                throw new Error(ex.message);
            }
        }
    }
    Parse.prototype.getFileObj = function (filePath) {
        var fileObj = {};
        try {
            var extname = path.extname(filePath);
            if (extname.indexOf('.yaml') !== -1 || extname.indexOf('.yml') !== -1) {
                fileObj = js_yaml_1.default.load(fs.readFileSync(filePath, 'utf8'));
            }
            if (extname.indexOf('.json') !== -1) {
                fileObj = JSON.parse(fs.readFileSync(filePath).toString());
            }
        }
        catch (e) {
            if (process.env['serverless_devs_out_put_help'] !== 'true') {
                (0, error_1.handleError)(e, 'Failed to execute:');
            }
        }
        return fileObj;
    };
    Parse.prototype.init = function (filePath) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.parsedObj = this.getFileObj(filePath);
                return [2 /*return*/];
            });
        });
    };
    Parse.prototype.getOriginalParsedObj = function () {
        return this.parsedObj;
    };
    Parse.prototype.findVariableValue = function (variableObj) {
        var variableName = variableObj.variableName, type = variableObj.type, funName = variableObj.funName, funVariable = variableObj.funVariable;
        var result = '';
        if (type === 'Literal') {
            // 兼容新版本的规范 services
            return (this.globalJsonKeyMap[variableName] ||
                this.globalJsonKeyMap["services." + variableName] ||
                '${' + variableName + '}');
        }
        if (type === 'Fun' && (funName === 'Env' || funName === 'env')) {
            return process.env[funVariable];
        }
        if (type === 'Fun' && (funName === 'Path' || funName === 'path')) {
            return path.join(process.cwd(), funVariable);
        }
        if (type === 'Fun' && (funName === 'File' || funName === 'file')) {
            return this.getFileObj(funVariable);
        }
        return result;
    };
    Parse.prototype.generateMagicVariables = function (value, arr, parentStr) {
        var _this = this;
        if (arr === void 0) { arr = []; }
        if (parentStr === void 0) { parentStr = ''; }
        if (Object.prototype.toString.call(value) === '[object Object]') {
            if (parentStr !== '') {
                parentStr = parentStr + ".";
            }
            Object.keys(value).map(function (key) {
                var showKey = "" + parentStr + key;
                var objValue = value[key];
                arr.push(showKey);
                arr.concat(_this.generateMagicVariables(objValue, arr, "" + showKey));
                _this.globalJsonKeyMap[showKey] = objValue;
            });
        }
        else if (Object.prototype.toString.call(value) === '[object Array]') {
            value.forEach(function (_arrValue, i) {
                var showKey = parentStr + "[" + i + "]";
                var showKeyNe = parentStr + "[" + (i - value.length) + "]";
                arr.push(showKey);
                arr.push(showKeyNe);
                arr.concat(_this.generateMagicVariables(_arrValue, arr, "" + showKey));
                arr.concat(_this.generateMagicVariables(_arrValue, arr, "" + showKeyNe));
                _this.globalJsonKeyMap[showKey] = _arrValue;
                _this.globalJsonKeyMap[showKeyNe] = _arrValue;
            });
        }
        else {
            arr = [];
        }
        return arr;
    };
    Parse.prototype.isProjectProperties = function (topKey, parentKey) {
        var projProperties = false;
        if (parentKey === 'Properties' && this.globalJsonKeyMap[topKey + "." + parentKey]) {
            projProperties = true;
        }
        return projProperties;
    };
    Parse.prototype.iteratorToSetValue = function (objValue, topKey, parentKey) {
        var _this = this;
        if (OTHER_BASIC_DATA_TYPE.includes(Object.prototype.toString.call(objValue))) {
            return objValue;
        }
        if (Object.prototype.toString.call(objValue) === '[object String]') {
            var regResult = objValue.match(COMMON_VARIABLE_TYPE_REG);
            if (regResult) {
                var matchResult = regResult[1]; // get match result like projectName.key.variable
                var variableObj = { variableName: matchResult, type: 'Literal', funName: null, funVariable: '' };
                var funMatchResult = matchResult.match(SPECIALL_VARIABLE_TYPE_REG);
                if (funMatchResult) {
                    variableObj.funName = funMatchResult[1];
                    variableObj.funVariable = funMatchResult[2];
                    variableObj.type = 'Fun';
                }
                else {
                    var topKeyDependenciesMap = this.dependenciesMap[topKey];
                    if (!topKeyDependenciesMap) {
                        topKeyDependenciesMap = {};
                    }
                    var dependProjName = matchResult.split('.')[0];
                    topKeyDependenciesMap[dependProjName] = 1; // Dependent priority
                    this.dependenciesMap[topKey] = topKeyDependenciesMap;
                }
                var realValue = this.findVariableValue(variableObj);
                return Object.prototype.toString.call(realValue) === '[object String]'
                    ? objValue.replace(COMMON_VARIABLE_TYPE_REG, realValue)
                    : realValue;
            }
            if (!this.dependenciesMap[topKey] || Object.keys(this.dependenciesMap[topKey]).length == 0) {
                this.dependenciesMap[topKey] = {};
            }
            return objValue;
        }
        if (Object.prototype.toString.call(objValue) === '[object Array]') {
            return objValue.map(function (item) {
                return _this.iteratorToSetValue(item, topKey);
            });
        }
        if (Object.prototype.toString.call(objValue) === '[object Object]') {
            Object.keys(objValue).forEach(function (key) {
                objValue[key] = _this.iteratorToSetValue(objValue[key], topKey, parentKey || key);
            });
            return objValue;
        }
    };
    Parse.prototype.replaceVariable = function (variable) {
        var _this = this;
        var _variable = (0, version_1.getServiceList)(variable);
        Object.keys(_variable).forEach(function (key) {
            var objValue = _variable[key];
            _variable[key] = _this.iteratorToSetValue(objValue, key);
        });
        if (variable.services) {
            variable.services = _variable;
        }
        else {
            variable = _variable;
        }
        return variable;
    };
    Parse.prototype.getRealVariables = function (parsedObj) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.globalKeyArr = this.generateMagicVariables(parsedObj);
                return [2 /*return*/, this.replaceVariable(parsedObj)];
            });
        });
    };
    return Parse;
}());
exports.Parse = Parse;
//# sourceMappingURL=data:application/json;base64, 