"use strict";
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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareStarter = exports.createApp = void 0;
const cli_spinner_1 = require("cli-spinner");
const fs = __importStar(require("fs"));
const path_1 = require("path");
const c = __importStar(require("colorette"));
const download_1 = require("./download");
const unzip_1 = require("./unzip");
const utils_1 = require("./utils");
const replace_in_file_1 = __importDefault(require("replace-in-file"));
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(c.bold('Preparing starter'));
        loading.setSpinnerString(18);
        loading.start();
        const startT = Date.now();
        try {
            const moveTo = yield prepareStarter(starter);
            if (!moveTo) {
                throw new Error('starter install failed');
            }
            yield moveTo(projectName);
        }
        finally {
            loading.stop(true);
        }
        const time = (0, utils_1.printDuration)(Date.now() - startT);
        (0, utils_2.log)(`${c.green('✔')} ${c.bold('All setup')} ${(0, utils_1.onlyUnix)('🎉')} ${c.dim(time)}

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

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

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


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

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

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

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