"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializeWebpack = exports.initializeThemekit = exports.initializeWorkingDirectory = void 0;
const path_1 = __importDefault(require("path"));
const chokidar_1 = __importDefault(require("chokidar"));
const ws_1 = __importDefault(require("ws"));
const cross_spawn_1 = __importDefault(require("cross-spawn"));
const _directorys_1 = __importDefault(require("../utils/_directorys"));
const _logUtils_1 = require("../utils/_logUtils");
const _fileHelpers_1 = require("../utils/_fileHelpers");
// Initialize the Working directory watcher, provides the event system for the watchers.
const initializeWorkingDirectory = () => {
    // creates a chokidar watcher to watch the src root.
    const watcher = chokidar_1.default.watch(_directorys_1.default.developmentRoot, {
        ignored: [
            _directorys_1.default.scriptsRoot,
            _directorys_1.default.stylesRoot,
            _directorys_1.default.assetsRoot,
            _directorys_1.default.productionRoot,
        ]
    });
    // Watch these files in the src root for changes on update, add & remove.
    watcher.on('change', _fileHelpers_1.updateFile);
    watcher.on('add', _fileHelpers_1.addFile);
    watcher.on('unlink', _fileHelpers_1.removeFile);
};
exports.initializeWorkingDirectory = initializeWorkingDirectory;
const initializeThemekit = (port, environment) => __awaiter(void 0, void 0, void 0, function* () {
    let environments = [];
    if (Object.prototype.hasOwnProperty.call(environment, "env")) {
        environments = environment['env'].split(' ');
    }
    const wss = new ws_1.default.Server({ port });
    let client = undefined;
    wss.on('connection', (ws) => client = ws);
    const liveReloadCallback = (data) => (typeof client != 'undefined' && data.includes('Updated')) ? client.send('event') : null;
    return new Promise((resolve) => {
        // Open the theme for each specified environment
        if (environments.length) {
            environments.forEach(env => {
                (0, cross_spawn_1.default)(_directorys_1.default.theme, ['open', `-e=${env}`], { stdio: 'pipe' });
            });
        }
        else {
            (0, cross_spawn_1.default)(_directorys_1.default.theme, ['open'], { stdio: 'pipe' });
        }
        // Start a themekit listener for each specified environment
        const themekitArguments = ['watch', `--dir=${path_1.default.resolve('./shop/dist')}`];
        environments.forEach(env => {
            themekitArguments.push(`-e=${env}`);
        });
        const command = (0, cross_spawn_1.default)(_directorys_1.default.theme, themekitArguments, { stdio: 'pipe' });
        command.stdout.on('data', data => {
            (0, _logUtils_1.spawnCallback)(data, false, liveReloadCallback);
            if (data.toString().includes('Watching for file changes'))
                resolve();
        });
        command.stderr.on('data', data => (0, _logUtils_1.spawnCallback)(data, false));
        command.on('error', err => (0, _logUtils_1.handleError)(err.errno, err));
    });
});
exports.initializeThemekit = initializeThemekit;
const initializeWebpack = () => {
    return new Promise((resolve) => {
        const command = (0, cross_spawn_1.default)('npx', ['webpack'], { stdio: 'pipe' });
        command.stdout.on('data', (data) => (0, _logUtils_1.spawnCallback)(data, false));
        command.stderr.on('data', (data) => (0, _logUtils_1.spawnCallback)(data, false));
        command.on('error', (err) => (0, _logUtils_1.handleError)(err.errno, err));
        resolve();
    });
};
exports.initializeWebpack = initializeWebpack;
