"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = require("os");
const chalk = require("chalk");
const cli_utils_1 = require("@ionic/cli-utils");
const cordova_1 = require("../lib/utils/cordova");
const configXmlUtils_1 = require("../lib/utils/configXmlUtils");
const setup_1 = require("../lib/utils/setup");
/**
 * Metadata about the run command
 */
let RunCommand = class RunCommand extends cli_utils_1.Command {
    run(inputs, options) {
        return __awaiter(this, void 0, void 0, function* () {
            const isLiveReload = options['livereload'];
            const runPlatform = inputs[0];
            if (runPlatform === 'ios' && os.platform() !== 'darwin') {
                this.env.log.error('You cannot run iOS unless you are on Mac OSX.');
                return;
            }
            var tasks = new cli_utils_1.TaskChain();
            yield Promise.all([
                setup_1.getProjectPlatforms(this.env.project.directory).then((platforms) => {
                    if (!platforms.includes(runPlatform)) {
                        tasks.next(`Installing the platform: ${chalk.bold('cordova platform add ' + runPlatform)}`);
                        return setup_1.installPlatform(runPlatform);
                    }
                    return Promise.resolve();
                }),
                setup_1.arePluginsInstalled(this.env.project.directory).then((areInstalled) => {
                    if (!areInstalled) {
                        tasks.next(`Installing the project plugins: ${chalk.bold('cordova plugin add --save <plugin>')}`);
                        return setup_1.installPlugins();
                    }
                    return Promise.resolve();
                })
            ]);
            // If it is not livereload then just run build.
            if (!isLiveReload) {
                // ensure the content node was set back to its original
                yield configXmlUtils_1.resetConfigXmlContentSrc(this.env.project.directory);
                tasks.end();
                yield this.env.emitter.emit('build', {
                    options: cordova_1.generateBuildOptions(this.metadata, options)
                });
                tasks.next(`Starting build`);
            }
            else {
                tasks.end();
                const serverSettings = (yield this.env.emitter.emit('serve', {
                    env: this.env,
                    options: cordova_1.generateBuildOptions(this.metadata, options),
                }))[0];
                yield configXmlUtils_1.writeConfigXmlContentSrc(this.env.project.directory, `http://${serverSettings.publicIp}:${serverSettings.httpPort}`);
                tasks.next(`Starting server`);
            }
            const optionList = cordova_1.filterArgumentsForCordova(this.metadata, inputs, options);
            tasks.next(`Executing cordova command: ${chalk.bold('cordova ' + optionList.join(' '))}`);
            yield this.env.shell.run('cordova', optionList, {
                showExecution: (this.env.log.level === 'debug')
            });
            tasks.end();
        });
    }
};
RunCommand = __decorate([
    cli_utils_1.CommandMetadata({
        name: 'run',
        description: 'Run an Ionic project on a connected device',
        exampleCommands: ['ios --livereload -c -s'],
        inputs: [
            {
                name: 'platform',
                description: `The platform to run: ${chalk.green('ios')}, ${chalk.green('android')}`,
                validators: [cli_utils_1.validators.required],
                prompt: {
                    message: `What platform would you like to run: ${chalk.green('ios')}, ${chalk.green('android')}`
                }
            }
        ],
        options: [
            // App Scripts Options
            {
                name: 'livereload',
                description: 'Live reload app dev files from the device',
                type: Boolean,
                aliases: ['l']
            },
            {
                name: 'address',
                description: 'Use specific address (livereload req.)',
                default: '0.0.0.0'
            },
            {
                name: 'consolelogs',
                description: 'Print app console logs to Ionic CLI',
                type: Boolean,
                aliases: ['c']
            },
            {
                name: 'serverlogs',
                description: 'Print dev server logs to Ionic CLI',
                type: Boolean,
                aliases: ['s']
            },
            {
                name: 'port',
                description: 'Dev server HTTP port',
                default: '8100',
                aliases: ['p']
            },
            {
                name: 'livereload-port',
                description: 'Live Reload port',
                default: '35729',
                aliases: ['r']
            },
            {
                name: 'prod',
                description: 'Create a prod build with app-scripts',
                type: Boolean
            },
            // Cordova Options
            {
                name: 'list',
                description: 'List all available Cordova run targets',
                type: Boolean,
                intent: cordova_1.CORDOVA_INTENT
            },
            {
                name: 'debug',
                description: 'Create a Cordova debug build',
                type: Boolean,
                intent: cordova_1.CORDOVA_INTENT
            },
            {
                name: 'release',
                description: 'Create a Cordova release build',
                type: Boolean,
                intent: cordova_1.CORDOVA_INTENT
            },
            {
                name: 'device',
                description: 'Deploy Cordova build to a device',
                type: Boolean,
                intent: cordova_1.CORDOVA_INTENT
            },
            {
                name: 'emulator',
                description: 'Deploy Cordova build to an emulator',
                type: Boolean,
                intent: cordova_1.CORDOVA_INTENT
            },
            {
                name: 'target',
                description: `Deploy Cordova build to a device (use ${chalk.green('--list')} to see all)`,
                type: String,
                intent: cordova_1.CORDOVA_INTENT
            }
        ]
    })
], RunCommand);
exports.RunCommand = RunCommand;
