"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 });
const cli_core_1 = require("@bluebase/cli-core");
const cli_flags_1 = require("../../cli-flags");
const command_1 = require("@oclif/command");
const hotDevelopment_1 = __importDefault(require("../../scripts/hotDevelopment"));
const fs_1 = __importDefault(require("fs"));
const configFiles_1 = __importDefault(require("../../configFiles"));
const path_1 = __importDefault(require("path"));
const rimraf_1 = __importDefault(require("rimraf"));
const shelljs_1 = __importDefault(require("shelljs"));
const webpack_1 = __importDefault(require("webpack"));
const deepmerge = require("deepmerge");
// import { webpackCompileDev } from '../../scripts/webpackCompileDev';
// import fromRoot from '../../scripts/fromRoot';
class CustomCommand extends command_1.Command {
    run() {
        return __awaiter(this, void 0, void 0, function* () {
            const parsed = this.parse(CustomCommand);
            const flags = parsed.flags;
            cli_core_1.Utils.logger.log({
                label: '@bluebase/cli/web',
                level: 'info',
                message: '🌏 Starting BlueBase on web...',
            });
            // Absolute path of build dir
            let appJsPath = cli_core_1.Utils.fromProjectRoot(flags.appJsPath);
            const buildDir = cli_core_1.Utils.fromProjectRoot(flags.buildDir);
            const configDir = cli_core_1.Utils.fromProjectRoot(flags.configDir);
            const customWebPackClientConfigPath = cli_core_1.Utils.fromProjectRoot(flags.webpackClientConfigPath);
            const customWebPackServerConfigPath = cli_core_1.Utils.fromProjectRoot(flags.webpackServerConfigPath);
            if (!fs_1.default.existsSync(appJsPath)) {
                appJsPath = path_1.default.resolve(__dirname, '../../client/App.js');
            }
            /////////////////////////////
            ///// Setup FileManager /////
            /////////////////////////////
            // Set config files
            const configFiles = configFiles_1.default(flags.configDir);
            const fileManager = new cli_core_1.FileManager('web', configFiles);
            yield fileManager.setup();
            ///////////////////////////
            ///// Clear build dir /////
            ///////////////////////////
            // Delete dir if already exists
            if (fs_1.default.existsSync(buildDir)) {
                rimraf_1.default.sync(buildDir);
            }
            // Create a new build dir
            shelljs_1.default.mkdir('-p', buildDir);
            ////////////////////////////
            ///// Generate Configs /////
            ////////////////////////////
            let clientConfigs = yield fileManager.Hooks.run(`web.client-config`, {}, { buildDir, configDir });
            let serverConfigs = yield fileManager.Hooks.run(`web.server-config`, {}, { buildDir, configDir });
            if (fs_1.default.existsSync(customWebPackClientConfigPath)) {
                const configs = require(customWebPackClientConfigPath);
                clientConfigs = deepmerge(configs, clientConfigs);
            }
            if (fs_1.default.existsSync(customWebPackServerConfigPath)) {
                const configs = require(customWebPackServerConfigPath);
                serverConfigs = deepmerge(configs, serverConfigs);
            }
            // Path to bluebase.js file
            const bluebaseJsPath = yield fileManager.resolveFilePath('bluebase');
            // const assetsDirPath = await fileManager.resolveFilePath('assets-dir');
            const assetsDirPath = path_1.default.join(configDir, 'assets');
            const baseWebpackBuildOptions = {
                appJsPath,
                assetsDirPath,
                bluebaseJsPath,
                buildDirPath: buildDir,
                configDirPath: configDir,
            };
            //////////////////////////
            ///// Client Configs /////
            //////////////////////////
            const webpackClientConfigs = yield fileManager.Hooks.run(`web.client-webpack-config`, {}, Object.assign({}, baseWebpackBuildOptions, { clientConfigs, configs: Object.assign({}, clientConfigs, { mode: 'development' }), serverConfigs }));
            const clientCompiler = webpack_1.default(webpackClientConfigs);
            //////////////////////////
            ///// Server Configs /////
            //////////////////////////
            cli_core_1.Utils.logger.log({
                label: '@bluebase/cli/web',
                level: 'info',
                message: `🎛 Compiling Webpack Server bundle`
            });
            const webpackServerConfigs = yield fileManager.Hooks.run(`web.server-webpack-config`, {}, Object.assign({}, baseWebpackBuildOptions, { clientConfigs, configs: Object.assign({}, serverConfigs, { mode: 'development' }), serverConfigs }));
            const serverCompiler = webpack_1.default(webpackServerConfigs);
            /////////////////
            ///// Build /////
            /////////////////
            cli_core_1.Utils.logger.log({
                label: '@bluebase/cli/web',
                level: 'info',
                message: `👨‍💻 Compiling Webpack Client bundle`
            });
            hotDevelopment_1.default(Object.assign({}, baseWebpackBuildOptions, { clientCompiler,
                clientConfigs,
                serverCompiler,
                serverConfigs,
                webpackClientConfigs,
                webpackServerConfigs }));
            // // Finish
            // Utils.logger.log({
            // 	label: '@bluebase/cli/web',
            // 	level: 'info',
            // 	message: '✅ Done!',
            // });
        });
    }
}
CustomCommand.flags = cli_flags_1.FlagDefs;
exports.CustomCommand = CustomCommand;
//# sourceMappingURL=start.js.map