"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const inquirer_1 = __importDefault(require("inquirer"));
const path_1 = __importDefault(require("path"));
const shelljs_1 = __importDefault(require("shelljs"));
const ejs = __importStar(require("ejs"));
const fs_1 = require("fs");
// create folder
function createProject(projectPath) {
    if ((0, fs_1.existsSync)(projectPath)) {
        console.log(`Folder ${projectPath} exists. Delete or use another name.`);
        return false;
    }
    console.log(" > Creating Folder");
    (0, fs_1.mkdirSync)(projectPath);
    return true;
}
// list of file/folder that should not be copied
const SKIP_FILES = ["node_modules", ".template.json"];
function createDirectoryContents(templatePath, filepath, options) {
    const filesToCreate = (0, fs_1.readdirSync)(templatePath);
    filesToCreate.forEach((file) => {
        const origFilePath = path_1.default.join(templatePath, file);
        const stats = (0, fs_1.statSync)(origFilePath);
        if (SKIP_FILES.indexOf(file) > -1)
            return;
        if (stats.isFile()) {
            const writePath = path_1.default.join(options.root, filepath, file);
            if ([".json", ".md", ".ts"].includes(path_1.default.extname(origFilePath))) {
                // use template rendering for text files
                let contents = (0, fs_1.readFileSync)(origFilePath, "utf8");
                contents = templateRender(contents, options);
                (0, fs_1.writeFileSync)(writePath, contents, "utf8");
            }
            else {
                // binary content (straight copy)
                (0, fs_1.copyFileSync)(origFilePath, writePath);
            }
        }
        else if (stats.isDirectory()) {
            if (!(0, fs_1.existsSync)(path_1.default.join(options.root, filepath, file))) {
                (0, fs_1.mkdirSync)(path_1.default.join(options.root, filepath, file));
            }
            createDirectoryContents(path_1.default.join(templatePath, file), path_1.default.join(filepath, file), options);
        }
    });
}
function templateRender(content, data) {
    return ejs.render(content, data);
}
function postProcess(options) {
    const isNode = (0, fs_1.existsSync)(path_1.default.join(options.templatePath, "package.json"));
    if (isNode) {
        shelljs_1.default.cd(options.targetPath);
        const result = shelljs_1.default.exec("yarn install");
        if (result.code !== 0) {
            return false;
        }
        const resultformat = shelljs_1.default.exec("yarn format");
        if (resultformat.code !== 0) {
            return false;
        }
    }
    return true;
}
exports.default = async (name, args) => {
    const root = path_1.default.resolve(".").replace(/\\/g, "/");
    const targetPath = path_1.default.join(root, name).replace(/\\/g, "/");
    if ((0, fs_1.existsSync)(targetPath))
        return console.log(`Folder ${targetPath} exists. Delete or use another name.`);
    console.log(args);
    const answers = await inquirer_1.default.prompt([
        {
            type: "list",
            name: "renderer",
            message: "Which project template do you want ?",
            when: () => !args.template?.trim(),
            choices: [
                { name: "2D (pixi.js)", value: "pixi" },
                { name: "3D (babylon.js)", value: "babylon" },
                { name: "Minimalist (canvas)", value: "mini" },
            ],
        },
        // {
        //   type: "list",
        //   name: "options",
        //   message: "Which type of build would you like for your Pixel Project ?",
        //   choices: [
        //     { name: "Web & Desktop App", value: "all" },
        //     { name: "HTML5 (Web Only)", value: "web" },
        //     { name: "Desktop (App Only)", value: "desktop" },
        //   ],
        // },
        {
            type: "checkbox",
            name: "features",
            message: "Which features do you need?",
            pageSize: 12,
            when: () => !args.features?.trim(),
            choices: [
                new inquirer_1.default.Separator(`--- Tooling ---`),
                {
                    name: "Git Integration",
                    checked: true,
                    value: "git",
                },
                {
                    name: "VSCode Integration (launch, debug, workspace)",
                    checked: true,
                    value: "vscode",
                },
                {
                    name: "Code style (Lint)",
                    value: "lint",
                    checked: true,
                },
                {
                    name: "Unit Testing",
                    checked: true,
                    value: "test",
                },
                {
                    name: "Github Actions (CI)",
                    value: "github",
                },
                new inquirer_1.default.Separator(`--- Features ---`),
                {
                    name: "Audio (Howler.js : https://howlerjs.com/)",
                    value: "physic",
                    checked: true,
                },
                {
                    name: "Localization (vue-i18n)",
                    value: "localization",
                },
                // {
                //   name: "Physics / Collision (P2.js : https://github.com/schteppe/p2.js/#demos)",
                //   value: "physic",
                // },
                // {
                //   name: "2D Character Animation (Spine : http://esotericsoftware.com/spine-demos )",
                //   value: "spine",
                // },
                // {
                //   name: "2D Layered Animations (Live2d : https://www.live2d.com/en/about/ )",
                //   value: "live2d",
                // },
            ],
        },
    ]);
    const getTemplate = (base, subfolder) => {
        return path_1.default.join(__dirname, "../..", base, subfolder).replace(/\\/g, "/");
    };
    // get values from either arg parameter or questions
    const renderer = args.template ? args.template : answers.renderer;
    const features = args.features ? args.features.split(",") : answers.features;
    const templatePath = getTemplate("templates", renderer);
    if (!createProject(targetPath))
        return;
    const options = {
        root,
        projectName: name.replace(/[\W_]/g, "-"),
        templatePath,
        targetPath,
        useLint: features.includes("lint"),
        useTest: features.includes("test"),
        useGit: features.includes("git"),
        useGithub: features.includes("github"),
        useVSCode: features.includes("vscode"),
    };
    console.log(" > Copying Files");
    createDirectoryContents(templatePath, name, options);
    console.log(answers);
    if (options.useGit) {
        console.log(" > Adding Git");
        createDirectoryContents(getTemplate("templates/features", "git"), name, options);
    }
    if (options.useVSCode) {
        console.log(" > Adding VSCode");
        createDirectoryContents(getTemplate("templates/features", "vscode"), name, options);
    }
    if (options.useLint) {
        console.log(" > Adding Lint");
        createDirectoryContents(getTemplate("templates/features", "lint"), name, options);
    }
    if (options.useTest) {
        console.log(" > Adding Test");
        createDirectoryContents(getTemplate("templates/features", "test"), name, options);
    }
    if (options.useGithub) {
        console.log(" > Adding Github Actions");
        createDirectoryContents(getTemplate("templates/features", "github"), name, options);
    }
    console.log(" > Installing Dependencies");
    postProcess(options);
    console.log("------");
    console.log(`Your "${options.projectName}" project is ready to use !`);
    console.log("Run the following:");
    console.log(` cd ${name}`);
    console.log(` yarn dev`);
    console.log(`And check README.md for more informations`);
    console.log("------");
};
