"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const path = require("path");
const codiac_common_1 = require("@codiac.io/codiac-common");
const data_1 = require("../ops/data");
const ops_1 = require("../ops");
const command_base_tenantless_1 = require("../command-base-tenantless");
class Init extends command_base_tenantless_1.CommandBaseTenantless {
    /** Hydrates the main components used for this command. */
    initializeCommandState() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    // Set up loggers
                    // let settings = new LoggerSettings([LogLevel.notice, LogLevel.warn, LogLevel.error, LogLevel.fatal]);
                    // let cliCfgRepo = new cliGlobalConfigRepo({ cliConfigDir: this.config.configDir, version: this.config.version });
                    // let cliCfg = await cliCfgRepo.read();
                    // if (cliCfg && cliCfg.verbosity) {
                    //   switch (cliCfg.verbosity) {
                    //     case Verbosity.detail:
                    //       settings.LogLevelsToShow.push(LogLevel.detail);
                    //       break;
                    //     case Verbosity.debug:
                    //       settings.LogLevelsToShow.push(LogLevel.detail);
                    //       settings.LogLevelsToShow.push(LogLevel.debug);
                    //       settings.LogLevelsToShow.push(LogLevel.trace);
                    //       break;
                    //   }
                    // }
                    // this.ioc.bind<LoggerSettings>(LoggerSettings).toConstantValue(settings);
                    // this.ioc.bind<IBetterLogger>(INTERFACES.IBetterLogger).to(BetterConsoleLogger);
                    this.state = {
                        logger: this.ioc.get(codiac_common_1.INTERFACES.IBetterLogger)
                    };
                    resolve(this.state);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    this.bootstrap();
                    let comp = yield this.initializeCommandState();
                    const { args, flags } = yield this.parse(Init); // this needs to happen first so help can override
                    // ----------------------------------------------------------
                    // STEP 1)   USER DIALOGUE.  ACQUIRE VALID CLONE URL AND DESTINATION FOLDER
                    // ----------------------------------------------------------
                    let directory = args.directory;
                    let cloneUrl = flags.clone;
                    let projectType = flags.projectType;
                    // see if they provided a valid url with init call
                    if (flags.clone) {
                        let isValidClone = this.validateUrl(flags.clone);
                        if (isValidClone) {
                            cloneUrl = flags.clone;
                        }
                        else {
                            while (!isValidClone) {
                                cloneUrl = yield this._ui.prompt("cloneUrl", 'Please enter a valid clone url for your repo');
                                isValidClone = this.validateUrl(cloneUrl);
                            }
                        }
                    }
                    this._ui.userMessage(`Initializing project folder: ${directory}`);
                    if (ops_1.CliPathWalker.isConfigRoot(directory)) {
                        let redo = yield this._ui.promptConfirm("reinit", this._styler.colorWarning('This folder is already a project root!  Re-initialize? ') + "(y/n)");
                        if (!redo) {
                            this.log('Operation cancelled.  No work was done.');
                            this.exit(0);
                        }
                    }
                    try {
                        // ----------------------------------------------------------
                        // STEP 2)   PROCESSING.  PERFORM THE ACTUAL INIT WORK
                        // ----------------------------------------------------------
                        comp.logger.detail(`Target folder for project root: ${directory}`);
                        let projectRoot = (path.isAbsolute(directory)) ? directory : path.join(process.cwd(), directory);
                        let projCfgRepo = new data_1.ProjectContextRepo({ projectRoot: projectRoot });
                        // { cliConfigDir: this.config.configDir, version: this.config.version }, 
                        let initializer = new ops_1.ProjectInitializer(this.config.root, this._ops, projCfgRepo, comp.logger);
                        let result = yield initializer.init(directory, projectType, cloneUrl);
                        if (result.success) {
                            this._ops.renderTitleBlock();
                            this.logger.notice(this._styler.colorGood("Init complete!!"));
                            this._ui.userMessage(this._styler.colorGood("Init complete!!"));
                        }
                        else if (result.error) {
                            this.logger.error(`Error initializing project: ${result.message}, ${result.error.message || ""}.`, result.error);
                            this._ui.userMessage(`Error initializing project: ${result.message}, ${result.error.message || ""}.`);
                        }
                        else {
                            this.logger.error(`Project initialization failed but without any error: ${result.message}.`);
                            this._ui.userMessage(`Project initialization failed but without any error: ${result.message}.`);
                        }
                    }
                    catch (err) {
                        comp.logger.error(`Error during init: ${err.message || ""}`, err);
                    }
                    resolve();
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    validateUrl(value) {
        const clone = (value) ? value : '';
        return clone.startsWith('git@') || clone.includes('https://') || clone.includes('http://') || clone.includes('ssh://') || clone.includes('git://') || clone.includes('gits://') || clone.includes('ftp://') || clone.includes('ftps://');
    }
}
exports.default = Init;
Init.description = 'Declares the given folder as a project root';
Init.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    clone: core_1.Flags.string({ char: 'c', required: false, description: '(Optional) The git repo from which to hydrate the project folder.' }),
    projectType: core_1.Flags.string({ char: 't', required: false, description: '(Optional) The type of Codiac project to scaffold.' })
    // verbose: flags.boolean({ char: 'v', description: 'render stdout for each command' })
};
Init.args = {
    directory: core_1.Args.string({ required: true, description: 'Path to the desired project root, relative to current directory.' })
};
//# sourceMappingURL=init.js.map