"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) {
    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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const commandline_1 = require("../../util/commandline");
const interaction_1 = require("../../util/interaction");
const util_1 = require("util");
const apis_1 = require("../../util/apis");
const validation_utils_1 = require("./lib/validation-utils");
const misc_1 = require("../../util/misc");
const chalk = require("chalk");
const _ = require("lodash");
const debug = require("debug")("appcenter-cli:commands:codepush:patch");
let PatchCommand = class PatchCommand extends commandline_1.AppCommand {
    constructor(args) {
        super(args);
    }
    run(client) {
        return __awaiter(this, void 0, void 0, function* () {
            const app = this.app;
            let release;
            if (!this.targetBinaryRange && _.isNil(this.isDisabled) && _.isNil(this.isMandatory) && !this.description && !this.rollout) {
                return commandline_1.failure(commandline_1.ErrorCodes.Exception, "At least one property must be specified to patch a release.");
            }
            const rollout = Number(this.rollout);
            if (this.rollout != null && (!Number.isSafeInteger(rollout) || !validation_utils_1.isValidRollout(rollout))) {
                return commandline_1.failure(commandline_1.ErrorCodes.Exception, `Rollout value should be integer value between ${chalk.bold("1")} and ${chalk.bold("100")}.`);
            }
            if (this.targetBinaryRange != null && !validation_utils_1.isValidRange(this.targetBinaryRange)) {
                return commandline_1.failure(commandline_1.ErrorCodes.Exception, "Invalid binary version(s) for a release.");
            }
            const patch = {
                targetBinaryRange: this.targetBinaryRange,
                description: this.description,
            };
            if (this.rollout != null) {
                patch.rollout = rollout;
            }
            if (this.isDisabled != null) {
                patch.isDisabled = this.isDisabled;
            }
            if (this.isMandatory != null) {
                patch.isMandatory = this.isMandatory;
            }
            if (this.releaseLabel == null || this.releaseLabel === "") {
                debug("Release label is not set, get latest...");
                this.releaseLabel = yield this.getLatestReleaseLabel(client, app);
            }
            try {
                const httpRequest = yield interaction_1.out.progress("Patching CodePush release...", apis_1.clientRequest((cb) => client.deploymentReleases.update(this.deploymentName, this.releaseLabel, patch, app.ownerName, app.appName, cb)));
                release = httpRequest.result;
                if (httpRequest.response.statusCode === 204) {
                    interaction_1.out.text(`No update for the ${chalk.bold(this.releaseLabel)} of ${this.identifier} app's ${chalk.bold(this.deploymentName)} deployment`);
                }
                else {
                    interaction_1.out.text(`Successfully updated the ${chalk.bold(release.label)} of ${this.identifier} app's ${chalk.bold(this.deploymentName)} deployment`);
                }
                return commandline_1.success();
            }
            catch (error) {
                debug(`Failed to patch Codepush deployment - ${util_1.inspect(error)}`);
                return commandline_1.failure(commandline_1.ErrorCodes.Exception, error.response.body);
            }
        });
    }
    getLatestReleaseLabel(client, app) {
        return __awaiter(this, void 0, void 0, function* () {
            let releases;
            try {
                const httpRequest = yield interaction_1.out.progress("Fetching latest release label...", apis_1.clientRequest((cb) => client.codePushDeploymentReleases.get(this.deploymentName, app.ownerName, app.appName, cb)));
                releases = httpRequest.result;
            }
            catch (error) {
                debug(`Failed to get list of CodePush deployments - ${util_1.inspect(error)}`);
                if (error.statusCode === 404) {
                    const appNotFoundErrorMsg = `The app ${this.identifier} does not exist. Please double check the name, and provide it in the form owner/appname. \nRun the command ${chalk.bold(`${misc_1.scriptName} apps list`)} to see what apps you have access to.`;
                    throw commandline_1.failure(commandline_1.ErrorCodes.NotFound, appNotFoundErrorMsg);
                }
                else if (error.statusCode === 400) {
                    const deploymentNotExistErrorMsg = `The deployment ${chalk.bold(this.deploymentName)} does not exist.`;
                    throw commandline_1.failure(commandline_1.ErrorCodes.Exception, deploymentNotExistErrorMsg);
                }
                else {
                    throw commandline_1.failure(commandline_1.ErrorCodes.Exception, error.response.body);
                }
            }
            if (releases && releases.length > 0) {
                return releases[releases.length - 1].label;
            }
            else {
                throw commandline_1.failure(commandline_1.ErrorCodes.NotFound, `Failed to find any release to patch for ${this.identifier} app's ${chalk.bold(this.deploymentName)} deployment`);
            }
        });
    }
};
__decorate([
    commandline_1.help("Specifies one existing deployment name."),
    commandline_1.required,
    commandline_1.name("deployment-name"),
    commandline_1.position(0)
], PatchCommand.prototype, "deploymentName", void 0);
__decorate([
    commandline_1.help("Specifies label of one existing release to update. (Defaults to the latest release within the specified deployment)"),
    commandline_1.longName("existing-release-label"),
    commandline_1.shortName("l"),
    commandline_1.hasArg
], PatchCommand.prototype, "releaseLabel", void 0);
__decorate([
    commandline_1.help("Specifies whether this release should be considered mandatory. (Putting -m flag means mandatory)"),
    commandline_1.shortName("m"),
    commandline_1.longName("mandatory"),
    commandline_1.defaultValue(null)
], PatchCommand.prototype, "isMandatory", void 0);
__decorate([
    commandline_1.help("Specifies whether this release should be immediately downloadable. (Putting -x flag means disabled)"),
    commandline_1.shortName("x"),
    commandline_1.longName("disabled"),
    commandline_1.defaultValue(null)
], PatchCommand.prototype, "isDisabled", void 0);
__decorate([
    commandline_1.help("Specifies binary app version(s) that specifies this release is targeting for. (The value must be a semver expression such as 1.1.0, ~1.2.3)"),
    commandline_1.shortName("t"),
    commandline_1.longName("target-binary-version"),
    commandline_1.hasArg
], PatchCommand.prototype, "targetBinaryRange", void 0);
__decorate([
    commandline_1.help("Specifies description of the changes made to the app with this release"),
    commandline_1.shortName("d"),
    commandline_1.longName("description"),
    commandline_1.hasArg
], PatchCommand.prototype, "description", void 0);
__decorate([
    commandline_1.help("Specifies percentage of users this release should be immediately available to. (The specified number must be an integer between 1 and 100)"),
    commandline_1.shortName("r"),
    commandline_1.longName("rollout"),
    commandline_1.hasArg
], PatchCommand.prototype, "rollout", void 0);
PatchCommand = __decorate([
    commandline_1.help("Update the metadata for an existing CodePush release")
], PatchCommand);
exports.default = PatchCommand;
