"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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 (g && (g = 0, op[0] && (_ = 0)), _) 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 };
};
exports.__esModule = true;
exports.createX = void 0;
var chalk_1 = __importDefault(require("chalk"));
var rd = __importStar(require("rd"));
var fs_extra_1 = __importDefault(require("fs-extra"));
var path_1 = require("path");
var fs_1 = require("fs");
var lodash_1 = require("lodash");
var yeoman_environment_1 = __importDefault(require("yeoman-environment"));
var local_app_1 = require("./local-app");
var yeoman_app_1 = require("./yeoman-app");
var index_1 = require("../../index");
var AppType = index_1.config.AppType, AppSourceType = index_1.config.AppSourceType, TemplateCopyType = index_1.config.TemplateCopyType, zeppFontIcon = index_1.config.zeppFontIcon;
var child_process_1 = require("child_process");
var projectPreInstall = function (dir) {
    return new Promise(function (resolve) {
        if (!fs_extra_1["default"].existsSync((0, path_1.join)(dir, 'package.json'))) {
            resolve(true);
            return;
        }
        (0, child_process_1.exec)("cd ".concat(dir, " && npm install"), function (error, stdout, stderr) {
            if (error) {
                console.error("npm install error: ".concat(error));
                process.exit(1);
            }
            console.log(stderr);
            resolve(stdout);
        });
    });
};
var createX = function (cwdPath, args, func, beforeFiles) {
    if (beforeFiles === void 0) { beforeFiles = []; }
    return __awaiter(void 0, void 0, void 0, function () {
        var cmd, _a, projectName, _b, configVersion, workDir, templateDir, localTemplatesDirMap, localTemplates, allOS, appTypes, genChoices, localChoices, watchfaceTemplateChoices, appTemplateChoices, workoutExtTemplateChoices, getTemplateChoices, templatesInit, env, generatorMate, generatorMateKeys, choicesValueFormat, answer, choosePkg;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    cmd = args._[0], _a = args.projectName, projectName = _a === void 0 ? '' : _a, _b = args.configVersion, configVersion = _b === void 0 ? 'v2' : _b;
                    workDir = cwdPath;
                    args.configVersion = (0, lodash_1.toLower)(configVersion);
                    templateDir = (0, path_1.resolve)(__dirname, "../../public/template".concat((0, lodash_1.toLower)(configVersion) === 'v3' ? '/config-version-v3' : ''));
                    localTemplatesDirMap = {
                        v1: (0, path_1.resolve)(templateDir, './os1.0'),
                        v2: (0, path_1.resolve)(templateDir, './os2.0'),
                        v3: (0, path_1.resolve)(templateDir, './os3.0'),
                        'v3.5': (0, path_1.resolve)(templateDir, './os3.5'),
                        v4: (0, path_1.resolve)(templateDir, './os4.0')
                    };
                    localTemplates = Object.keys(localTemplatesDirMap).reduce(function (temps, osVersion) {
                        var dir = localTemplatesDirMap[osVersion];
                        var appDir = "".concat(dir, "/app");
                        var watchfaceDir = "".concat(dir, "/watchface");
                        var workoutExtensionDir = "".concat(dir, "/workout-extension");
                        temps[osVersion] = {
                            app: (0, fs_1.existsSync)(appDir) ? (0, fs_1.readdirSync)(appDir) : [],
                            watchface: (0, fs_1.existsSync)(watchfaceDir) ? (0, fs_1.readdirSync)(watchfaceDir) : [],
                            'workout-extension': (0, fs_1.existsSync)(workoutExtensionDir) ? (0, fs_1.readdirSync)(workoutExtensionDir) : []
                        };
                        return temps;
                    }, {});
                    allOS = ['v1', 'v2', 'v3', 'v3.5', 'v4'];
                    appTypes = ['watchface', 'app', 'workout-extension'];
                    genChoices = function () { return allOS.reduce(function (pre, osVersion) {
                        pre[osVersion] = [];
                        return pre;
                    }, {}); };
                    localChoices = genChoices();
                    watchfaceTemplateChoices = { v1: [], v2: [] };
                    appTemplateChoices = genChoices();
                    workoutExtTemplateChoices = { 'v3.5': [] };
                    getTemplateChoices = function (appType) {
                        switch (appType) {
                            case 'app': return appTemplateChoices;
                            case 'watchface': return watchfaceTemplateChoices;
                            case 'workout-extension': return workoutExtTemplateChoices;
                        }
                    };
                    templatesInit = function (os, dir) {
                        var initTemp = function (appType, dirPath, dirName) {
                            var tempChoices = getTemplateChoices(appType);
                            var tempName = (0, lodash_1.startCase)(dirName);
                            var chooseItem = {
                                name: tempName,
                                path: dirPath,
                                type: AppSourceType.LOCAL
                            };
                            if (tempName === 'Empty') {
                                Object.assign(chooseItem, {
                                    copyType: TemplateCopyType.EDIT
                                });
                                localChoices[os].unshift(chooseItem);
                                tempChoices[os].unshift(chooseItem);
                            }
                            else {
                                tempChoices[os].push(chooseItem);
                            }
                        };
                        appTypes.forEach(function (appType) {
                            localTemplates[os][appType].forEach(function (dirName) {
                                var dirPath = "".concat(dir, "/").concat(appType, "/").concat(dirName);
                                var dirStat = (0, fs_1.lstatSync)(dirPath);
                                if (!dirStat.isDirectory())
                                    return;
                                initTemp(appType, dirPath, dirName);
                            });
                        });
                    };
                    if (!(0, lodash_1.isEmpty)(localTemplates)) {
                        allOS.forEach(function (osVersion) {
                            templatesInit(osVersion, localTemplatesDirMap[osVersion]);
                        });
                    }
                    env = yeoman_environment_1["default"].createEnv();
                    env.lookup();
                    generatorMate = env.getGeneratorsMeta();
                    generatorMateKeys = Object.keys(generatorMate);
                    if (generatorMateKeys.length) {
                        generatorMateKeys.forEach(function (name) {
                            if (/:(app|all)$/.test(name)) {
                                allOS.forEach(function (osVersion) {
                                    localChoices[osVersion].push({
                                        name: name,
                                        type: AppSourceType.YEOMAN
                                    });
                                    appTemplateChoices[osVersion].push({
                                        name: name,
                                        type: AppSourceType.YEOMAN
                                    });
                                    watchfaceTemplateChoices[osVersion].push({
                                        name: name,
                                        type: AppSourceType.YEOMAN
                                    });
                                });
                            }
                        });
                    }
                    choicesValueFormat = function (arr) {
                        allOS.forEach(function (osVersion) {
                            if (!Array.isArray(arr[osVersion]))
                                return;
                            arr[osVersion].map(function (val, index) { return (val.value = index); });
                        });
                    };
                    choicesValueFormat(localChoices);
                    choicesValueFormat(appTemplateChoices);
                    choicesValueFormat(workoutExtTemplateChoices);
                    choicesValueFormat(watchfaceTemplateChoices);
                    return [4, func(args, {
                            appTemplateChoices: appTemplateChoices,
                            workoutExtTemplateChoices: workoutExtTemplateChoices,
                            watchfaceTemplateChoices: watchfaceTemplateChoices
                        })];
                case 1:
                    answer = _c.sent();
                    answer.appType = answer.appType || AppType.APP;
                    answer.workDir = workDir;
                    choosePkg = (function (appType) {
                        switch (appType.toLowerCase()) {
                            case AppType.APP: return appTemplateChoices[answer.OSVersion][answer.template];
                            case AppType.WORKOUT_EXTENSION: return workoutExtTemplateChoices[answer.OSVersion][answer.template];
                            case AppType.WATCHFACE: return watchfaceTemplateChoices[answer.OSVersion][answer.template];
                            default: return appTemplateChoices[answer.OSVersion][answer.template];
                        }
                    })(answer.appType || AppType.APP);
                    index_1.logger.info('fetching template...');
                    return [4, (0, index_1.sleep)(100)];
                case 2:
                    _c.sent();
                    if (choosePkg.type === AppSourceType.YEOMAN) {
                        index_1.logger.info("".concat((0, lodash_1.upperFirst)(cmd), " application using yeoman template \"").concat(choosePkg.name, "\"."));
                        (0, yeoman_app_1.createYeomanApp)(__assign(__assign({}, answer), { env: env, templateInfo: generatorMate[choosePkg.name] }));
                    }
                    else {
                        index_1.logger.info("".concat((0, lodash_1.upperFirst)(cmd), " application using local template \"").concat(choosePkg.name, "\"."));
                        (0, local_app_1.createLocalApp)(__assign(__assign({}, answer), { templateInfo: choosePkg }));
                    }
                    index_1.logger.log('\n');
                    return [4, (0, index_1.sleep)(50)];
                case 3:
                    _c.sent();
                    rd.eachFileSync(workDir, function (file) {
                        if ((0, lodash_1.endsWith)(file, '.DS_Store')) {
                            fs_extra_1["default"].remove(file);
                        }
                        else {
                            var shortFile = file.replace(cwdPath, '');
                            if (beforeFiles.includes(file)) {
                                index_1.logger.log(chalk_1["default"].yellow("  ".concat(chalk_1["default"].bold('replace'), "  ")), shortFile);
                            }
                            else {
                                index_1.logger.log(chalk_1["default"].green("   ".concat(chalk_1["default"].bold('create'), "  ")), shortFile);
                            }
                        }
                    });
                    index_1.logger.log('\n');
                    index_1.logger.success("Project created successfully by \"".concat(choosePkg.name, "\" template."));
                    index_1.logger.log('Start installing dependency packages.');
                    return [4, projectPreInstall(workDir)];
                case 4:
                    _c.sent();
                    index_1.logger.log(chalk_1["default"].hex('#DB8C41')(zeppFontIcon));
                    index_1.logger.log("I'm all done. Now you can start your application.");
                    return [2, [
                            "Project created successfully by \"".concat(choosePkg.name, "\" template."),
                            "I'm all done. Now you can start your application.",
                        ]];
            }
        });
    });
};
exports.createX = createX;
