"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const cli_spinner_1 = require("cli-spinner");
const fs = require("fs");
const path_1 = require("path");
const tc = require("turbocolor");
const download_1 = require("./download");
const unzip_1 = require("./unzip");
const utils_1 = require("./utils");
const _replace = require("replace-in-file");
// Fix types
const replace = _replace;
const utils_2 = require("../utils");
const starterCache = new Map();
function createApp(starter, projectName, autoRun) {
    return __awaiter(this, void 0, void 0, function* () {
        if (fs.existsSync(projectName)) {
            throw new Error(`Folder "./${projectName}" already exists, please choose a different project name.`);
        }
        projectName = projectName.toLowerCase().trim();
        if (!validateProjectName(projectName)) {
            throw new Error(`Project name "${projectName}" is not valid. It must be a kebab-case name without spaces.`);
        }
        const loading = new cli_spinner_1.Spinner(tc.bold('Preparing starter'));
        loading.setSpinnerString(18);
        loading.start();
        const startT = Date.now();
        const moveTo = yield prepareStarter(starter);
        if (!moveTo) {
            throw new Error('starter install failed');
        }
        yield moveTo(projectName);
        loading.stop(true);
        const time = utils_1.printDuration(Date.now() - startT);
        utils_2.log(`${tc.green('✔')} ${tc.bold('All setup')} ${utils_1.onlyUnix('🎉')} ${tc.dim(time)}

  ${tc.dim(utils_1.terminalPrompt())} ${tc.green('npm start')}
    Starts the development server.

  ${tc.dim(utils_1.terminalPrompt())} ${tc.green('npm run build')}
    Builds your app in production mode.

  ${tc.dim(utils_1.terminalPrompt())} ${tc.green('npm test')}
    Starts the test runner.


  ${tc.dim('We suggest that you begin by typing:')}

   ${tc.dim(utils_1.terminalPrompt())} ${tc.green('cd')} ${projectName}
   ${tc.dim(utils_1.terminalPrompt())} ${tc.green('npm start')}
${renderDocs(starter)}

  Happy coding! 🎈
`);
        if (autoRun) {
            yield utils_1.npm('start', projectName, 'inherit');
        }
    });
}
exports.createApp = createApp;
function renderDocs(starter) {
    const docs = starter.docs;
    if (!docs) {
        return '';
    }
    return `
  ${tc.dim('Further reading:')}

   ${tc.dim('-')} ${tc.cyan(docs)}`;
}
function prepareStarter(starter) {
    let promise = starterCache.get(starter);
    if (!promise) {
        promise = prepare(starter);
        // silent crash, we will handle later
        promise.catch(() => {
            return;
        });
        starterCache.set(starter, promise);
    }
    return promise;
}
exports.prepareStarter = prepareStarter;
function prepare(starter) {
    return __awaiter(this, void 0, void 0, function* () {
        const baseDir = process.cwd();
        const tmpPath = path_1.join(baseDir, '.tmp-flow-starter');
        const buffer = yield download_1.downloadStarter(starter);
        utils_1.setTmpDirectory(tmpPath);
        yield unzip_1.unZipBuffer(buffer, tmpPath);
        yield utils_1.npm('ci', tmpPath);
        return (projectName) => __awaiter(this, void 0, void 0, function* () {
            const filePath = path_1.join(baseDir, projectName);
            yield utils_1.renameAsync(tmpPath, filePath);
            yield replace({
                files: [path_1.join(filePath, '*'), path_1.join(filePath, 'config/**'), path_1.join(filePath, 'src/**')],
                from: /flow-starter-project-name/g,
                to: projectName,
                allowEmptyPaths: true
            });
            utils_1.setTmpDirectory(null);
        });
    });
}
function validateProjectName(projectName) {
    return !/[^a-zA-Z0-9-]/.test(projectName);
}
//# sourceMappingURL=create-app.js.map