"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = require("@salesforce/command");
const core_1 = require("@salesforce/core");
const Project_1 = __importDefault(require("../../../../../common/Project"));
const LocalDevServer_1 = __importDefault(require("../../../../../server/LocalDevServer"));
const debug_1 = __importDefault(require("debug"));
const colors_1 = __importDefault(require("colors"));
const debug = debug_1.default('localdevserver');
core_1.Messages.importMessagesDirectory(__dirname);
const messages = core_1.Messages.loadMessages('@salesforce/lwc-dev-server', 'start');
class Start extends command_1.SfdxCommand {
    async run() {
        const devhubusername = this.hubOrg ? this.hubOrg.getUsername() : '';
        const devhubalias = this.configAggregator.getPropertyValue('defaultdevhubusername');
        let port;
        if (this.flags.port !== undefined && this.flags.port !== null) {
            port = this.flags.port;
        }
        else {
            port = 3333;
        }
        if (!this.org) {
            const targetusername = this.flags.targetusername;
            if (targetusername) {
                this.reportStatus(colors_1.default.green(devhubalias), colors_1.default.red(`${targetusername} - ${messages.getMessage('error:invalidscratchorgusername')}`));
            }
            else {
                const configuredusername = this.configAggregator.getPropertyValue('defaultusername');
                this.reportStatus(colors_1.default.green(devhubalias), colors_1.default.red(`${configuredusername} - ${messages.getMessage('error:noscratchorg')}`));
            }
            return { org: typeof this.org };
        }
        if (!this.project) {
            this.ux.error(messages.getMessage('error:noproject'));
            return { project: typeof this.project };
        }
        this.ux.log(colors_1.default.gray(messages.getMessage('legal:cliusage')));
        const conn = this.org.getConnection();
        const api_version = await conn.retrieveMaxApiVersion();
        const orgusername = this.org.getUsername() || '';
        try {
            process.on('unhandledRejection', reason => {
                if (reason &&
                    reason.name &&
                    reason.name === 'StatusCodeError') {
                    debug(`unhandledPromiseRejection: ${reason}`);
                }
                else {
                    this.ux.error(`unhandledPromiseRejection: ${reason}`);
                }
            });
            await this.org.refreshAuth();
        }
        catch (err) {
            this.reportStatus(colors_1.default.green(devhubalias), colors_1.default.red(`${orgusername} - ${messages.getMessage('error:inactivescratchorg')}`), colors_1.default.green(api_version));
            return { error: err };
        }
        this.reportStatus(colors_1.default.green(devhubalias), colors_1.default.green(orgusername), colors_1.default.green(api_version));
        const accessToken = conn.accessToken;
        const onProxyReq = function (proxyReq, req, res) {
            proxyReq.setHeader('Authorization', `Bearer ${accessToken}`);
        };
        const project = new Project_1.default(this.project.getPath());
        project.configuration.api_version = api_version;
        project.configuration.endpoint = conn.instanceUrl;
        project.configuration.onProxyReq = onProxyReq;
        project.configuration.port = port;
        project.configuration.namespace = ((await this.project.resolveProjectConfig()).namespace);
        const retValue = {
            orgId: this.org.getOrgId(),
            api_version: project.configuration.api_version,
            endpoint: project.configuration.endpoint,
            onProxyReq: JSON.stringify(project.configuration.onProxyReq),
            port,
            token: accessToken
        };
        debug(JSON.stringify({ ...retValue, token: undefined }));
        new LocalDevServer_1.default(devhubusername).start(project, conn);
        return retValue;
    }
    reportStatus(devHubOrg, scratchOrg, apiVersion) {
        if (apiVersion) {
            this.ux.log(`\
Starting LWC Local Development.
    Dev Hub Org: ${devHubOrg}
    Scratch Org: ${scratchOrg}
    Api Version: ${apiVersion}\
`);
        }
        else {
            this.ux.log(`\
Starting LWC Local Development.
    Dev Hub Org: ${devHubOrg}
    Scratch Org: ${scratchOrg}\
`);
        }
    }
}
exports.default = Start;
Start.description = messages.getMessage('commandDescription');
Start.examples = [
    `$ sfdx force:lighting:lwc:start`,
    `$ sfdx force:lighting:lwc:start --port 3000`
];
Start.args = [];
Start.flagsConfig = {
    port: command_1.flags.integer({
        char: 'p',
        description: messages.getMessage('portFlagDescription')
    })
};
Start.supportsUsername = true;
Start.supportsDevhubUsername = true;
Start.requiresProject = true;
//# sourceMappingURL=start.js.map