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());
    });
};
const { api } = require('./index');
const ip = require('ip').address();
const path = require('path');
const uuid = require('uuid');
const detect = require('detect-port');
const compile = require('../builder').default;
const chalk = require('chalk');
module.exports = {
    run(source) {
        return __awaiter(this, void 0, void 0, function* () {
            const options = {};
            let devtoolOptions = yield transformOptions(options);
            let shouldReload = false;
            if (source) {
                yield compile(source, path.join(__dirname, '../../frontend/public/weex'), {
                    watch: true,
                    filename: '[name].js',
                    web: false,
                    config: options.config || options.c,
                    ip: devtoolOptions.ip,
                    port: devtoolOptions.port,
                    BUNDLE_DIRECTORY: 'public/weex'
                }, (error, output, json) => __awaiter(this, void 0, void 0, function* () {
                    let bundles = [];
                    if (error) {
                        console.log(chalk.red(Array.isArray(error) ? error.join('\n') : error));
                    }
                    else {
                        bundles = json.assets.map(asset => {
                            let entry;
                            let date = new Date();
                            const formateTime = (value) => {
                                return value < 10 ? '0' + value : value;
                            };
                            if (/\./.test(source)) {
                                entry = path.resolve(source);
                            }
                            else {
                                entry = path.resolve(source, asset.name.replace('.js', '.vue'));
                            }
                            return {
                                updateTime: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDay()} ${formateTime(date.getHours())}:${formateTime(date.getMinutes())}:${formateTime(date.getSeconds())}`,
                                output: `http://${ip}:${devtoolOptions.port}/weex/${asset.name}?bundleType=vue`,
                                size: (asset.size / 1024).toFixed(0),
                                time: json.time,
                                entry: entry
                            };
                        });
                    }
                    if (!shouldReload) {
                        shouldReload = true;
                        yield api.startDevtoolServer(bundles, devtoolOptions);
                    }
                    else {
                        api.reload();
                    }
                }));
            }
            else {
                yield api.startDevtoolServer([], devtoolOptions);
            }
        });
    }
};
const transformOptions = (options) => __awaiter(this, void 0, void 0, function* () {
    let defaultPort = yield detect(8089);
    return {
        ip: options.host,
        port: options.port || options.p || defaultPort,
        channelId: options.channelid || uuid(),
        manual: options.manual,
        remoteDebugPort: options.remoteDebugPort
    };
});
