#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const chalk_1 = __importDefault(require("chalk"));
const prompts_1 = __importDefault(require("prompts"));
const child_process_1 = require("child_process");
const console_1 = require("console");
const comment_json_1 = require("comment-json");
const customtypes_1 = require("./customtypes");
(async () => {
    const banner = chalk_1.default `
                _|_|                                        _|    _|                
    _|_|_|    _|        _|_|_|    _|_|_|                _|_|_|  _|_|_|_|    _|_|_|  
  _|_|      _|_|_|_|  _|        _|        _|_|_|_|_|  _|    _|    _|      _|_|      
      _|_|    _|      _|        _|                    _|    _|    _|          _|_|  
  _|_|_|      _|        _|_|_|    _|_|_|                _|_|_|      _|_|  _|_|_|    
                                                                                    
                                                                    `;
    console_1.log(chalk_1.default.hex('ed26f3')(banner));
    console_1.log(`Welcome to ${chalk_1.default.magentaBright('sfcc-dts')} interactive project setup wizard.\n`);
    const response = await prompts_1.default([{
            type: 'text',
            name: 'cartridgeroot',
            message: 'Directory containing your cartridges?',
            initial: './cartridges/',
            validate: value => !fs_1.default.existsSync(value) ? `Directory ${value} does not exists` : true
        },
        {
            type: 'text',
            name: 'meta',
            message: 'Directory containing system-objecttype-extensions.xml?',
            initial: './sites/site_template/meta/',
            validate: value => !fs_1.default.existsSync(value) ? `directory ${value} not found` : true
        }
    ]);
    let cartridgeroot = response.cartridgeroot;
    let extensions = response.meta;
    console_1.log(`Ready to go, will setup the project using cartridges in ${cartridgeroot} and custom attributes definition in ${extensions}\n`);
    let tsconfig = {};
    if (fs_1.default.existsSync('tsconfig.json')) {
        console_1.log('Checking existing tsconfig.json');
        tsconfig = comment_json_1.parse(fs_1.default.readFileSync('tsconfig.json', 'utf8'));
    }
    else {
        console_1.log('Creating new tsconfig.json');
    }
    if (!tsconfig.compilerOptions) {
        tsconfig.compilerOptions = {};
    }
    if (!tsconfig.compilerOptions.plugins) {
        tsconfig.compilerOptions.plugins = [];
    }
    if (tsconfig.compilerOptions.plugins.filter((i) => i.name === 'sfcc-dts').length === 0) {
        console_1.log('Adding sfcc-dts typescript plugin');
        tsconfig.compilerOptions.plugins.push({ "name": "sfcc-dts" });
    }
    let requiredoptions = {
        "module": "commonjs",
        "target": "es5",
        "noEmit": false,
        "allowJs": true,
        "checkJs": true,
        "esModuleInterop": true,
        "moduleResolution": "node"
    };
    Object.keys(requiredoptions).forEach(i => {
        if (tsconfig.compilerOptions.module !== 'commonjs') {
            console_1.log(`Setting compiler option ${i} to ${requiredoptions[i]}`);
            tsconfig.compilerOptions[i] = requiredoptions[i];
        }
    });
    if (!tsconfig.compilerOptions.paths) {
        tsconfig.compilerOptions.paths = {};
    }
    if (!tsconfig.compilerOptions.paths['dw/*'] || tsconfig.compilerOptions.paths['dw/*'].length !== 1 || tsconfig.compilerOptions.paths['dw/*'][0] !== "./node_modules/sfcc-dts/@types/sfcc/dw/*") {
        console_1.log(`Adding dw/* path`);
        tsconfig.compilerOptions.paths['dw/*'] = ["./node_modules/sfcc-dts/@types/sfcc/dw/*"];
    }
    if (!tsconfig.compilerOptions.paths['server'] || tsconfig.compilerOptions.paths['server'].length !== 1 || tsconfig.compilerOptions.paths['server'][0] !== `${cartridgeroot}/modules/server`) {
        console_1.log(`Adding server path`);
        tsconfig.compilerOptions.paths['server'] = [`${path_1.default.join(cartridgeroot, 'modules/server')}`];
        tsconfig.compilerOptions.paths['server/*'] = [`${path_1.default.join(cartridgeroot, 'modules/server/*')}`];
    }
    let cartridges = fs_1.default.readdirSync(cartridgeroot).filter(i => fs_1.default.lstatSync(path_1.default.join(cartridgeroot, i)).isDirectory() || fs_1.default.lstatSync(path_1.default.join(cartridgeroot, i)).isSymbolicLink()).filter(i => fs_1.default.existsSync(path_1.default.join(path_1.default.join(cartridgeroot, i), 'cartridge')));
    console_1.log(`Adding cartridge path`);
    tsconfig.compilerOptions.paths['~/*'] = cartridges.map(i => `${path_1.default.join(cartridgeroot, i)}/*`);
    cartridges.forEach(i => {
        tsconfig.compilerOptions.paths[`${i}/*`] = [`${path_1.default.join(cartridgeroot, i)}/*`];
    });
    // removing deprecated _star_ path
    tsconfig.compilerOptions.paths['_star_/*'] = undefined;
    console_1.log(`Write tscconfig.json`);
    fs_1.default.writeFileSync('tsconfig.json', comment_json_1.stringify(tsconfig, null, 2));
    let packagejson = comment_json_1.parse(fs_1.default.readFileSync('package.json', 'utf8'));
    if (!packagejson.devDependencies || !packagejson.devDependencies['sfcc-dts']) {
        console_1.log(`Installing local copy of sfcc-dts`);
        child_process_1.execSync('npm install --save-dev sfcc-dts@latest typescript@latest', { stdio: 'inherit' });
    }
    if ((packagejson.dependencies && packagejson.dependencies['dw-api']) || (packagejson.devDependencies && packagejson.devDependencies['dw-api'])) {
        console_1.log(`Uninstalling dw-api`);
        child_process_1.execSync('npm uninstall --save dw-api', { stdio: 'inherit' });
    }
    if (!fs_1.default.existsSync('@types')) {
        console_1.log(`Creating @types folder`);
        fs_1.default.mkdirSync('@types');
    }
    if (!fs_1.default.existsSync('@types/dw')) {
        console_1.log(`Creating @types/dw folder`);
        fs_1.default.mkdirSync(path_1.default.join('@types', 'dw'));
    }
    console_1.log(`Generating definitions for custom attributes`);
    if (extensions) {
        await customtypes_1.generateCustomTypes(extensions);
    }
    console_1.log(`Write @types/dw/index.d.ts`);
    let references = '/// <reference path="../../node_modules/sfcc-dts/@types/sfcc/index.d.ts" />\n';
    if (extensions) {
        references += '/// <reference path="./attrs.d.ts" />\n';
    }
    else {
        references += '/// <reference path="../../node_modules/sfcc-dts/@types/sfcc/attrs.d.ts" />\n';
    }
    fs_1.default.writeFileSync(path_1.default.join('@types/dw', 'index.d.ts'), references);
    console_1.log(`\nDone!`);
})();
