"use strict";
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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const path_resolver_1 = require("root/services/path-resolver");
const models_1 = require("root/models");
var EnvType;
(function (EnvType) {
    EnvType["TEST"] = "test";
    EnvType["DEV"] = "dev";
    EnvType["DEPLOY"] = "deploy";
})(EnvType = exports.EnvType || (exports.EnvType = {}));
var EnvStage;
(function (EnvStage) {
    EnvStage["PREPROD"] = "dev";
    EnvStage["PRODUCTION"] = "prod";
})(EnvStage = exports.EnvStage || (exports.EnvStage = {}));
class Env {
    static get envsJsonPath() {
        return path_1.default.join(path_resolver_1.getPrjRoot(), 'envs.json');
    }
    static getList() {
        return __awaiter(this, void 0, void 0, function* () {
            const file = yield fs_1.promises.readFile(Env.envsJsonPath);
            const jsonEnvs = JSON.parse(file.toString());
            return jsonEnvs.map(jsonEnv => {
                const env = new Env();
                env.id = jsonEnv.id;
                env.name = jsonEnv.name;
                env.type = jsonEnv.type;
                env.stage = jsonEnv.stage;
                return env;
            });
        });
    }
    static saveList(envs) {
        return __awaiter(this, void 0, void 0, function* () {
            const jsonEnvs = envs.map(env => (Object.assign({}, env)));
            yield fs_1.promises.writeFile(Env.envsJsonPath, JSON.stringify(jsonEnvs, null, 2));
        });
    }
    create(name) {
        var _a, _b, _c, _d;
        return __awaiter(this, void 0, void 0, function* () {
            this.name = name;
            this.type = EnvType.DEV;
            this.stage = null;
            const envs = yield Env.getList();
            this.id = (envs
                .map(endpoint => endpoint.id)
                .reduce((max, curr) => Math.max(max, curr), 0) || 0) + 1;
            envs.push(this);
            yield Env.saveList(envs);
            const envPath = path_1.default.join(path_resolver_1.getPrjRoot(), 'envs', `${name}.json`);
            yield fs_1.promises.writeFile(envPath, JSON.stringify({ name }, null, 2));
            const packageJsonPath = path_1.default.join(path_resolver_1.getPrjRoot(), 'package.json');
            const packageJson = require(packageJsonPath);
            packageJson.scripts = ((_a = packageJson) === null || _a === void 0 ? void 0 : _a.scripts) || {};
            if ((_d = (_c = (_b = packageJson) === null || _b === void 0 ? void 0 : _b.scripts) === null || _c === void 0 ? void 0 : _c[`DEV:${name}`], (_d !== null && _d !== void 0 ? _d : null)) === null) {
                packageJson.scripts[`DEV:${name}`] = `cp envs/${name}.json env.json && tsc && RLN_ENV=${name} serverless offline --host 0.0.0.0`;
            }
            else {
                console.warn(`Package Json Script command already found: DEV:${name}`);
            }
            yield fs_1.promises.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));
            const daos = yield models_1.Dao.getList(true);
            for (let dao of daos) {
                try {
                    yield dao.module.postEnvCreated(path_resolver_1.getPrjRoot(), name);
                }
                catch (e) {
                    console.error(`Error when calling afterEnvCreated hook on dao: ${dao.name} (${dao.id})`, e);
                }
            }
        });
    }
}
exports.default = Env;
//# sourceMappingURL=index.js.map