"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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandOptions = void 0;
/*
 *
 * Copyright 2018-present NEM
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
const clime_1 = require("clime");
const symbol_sdk_1 = require("symbol-sdk");
const announce_transactions_options_1 = require("../../interfaces/announce.transactions.options");
const profile_command_1 = require("../../interfaces/profile.command");
const options_resolver_1 = require("../../options-resolver");
const hash_resolver_1 = require("../../resolvers/hash.resolver");
const password_resolver_1 = require("../../resolvers/password.resolver");
const transactionInputType_resolver_1 = require("../../resolvers/transactionInputType.resolver");
const formatter_service_1 = require("../../services/formatter.service");
const transaction_view_1 = require("../../views/transactions/details/transaction.view");
class CommandOptions extends announce_transactions_options_1.AnnounceTransactionsOptions {
}
__decorate([
    (0, clime_1.option)({
        flag: 'i',
        description: 'Transaction input type (hash or payload).',
    }),
    __metadata("design:type", String)
], CommandOptions.prototype, "transactionInputType", void 0);
__decorate([
    (0, clime_1.option)({
        flag: 'h',
        description: 'Aggregate bonded transaction hash to be signed.',
    }),
    __metadata("design:type", String)
], CommandOptions.prototype, "hash", void 0);
__decorate([
    (0, clime_1.option)({
        flag: 'p',
        description: 'Aggregate transaction payload to be signed (hex string).',
    }),
    __metadata("design:type", String)
], CommandOptions.prototype, "payload", void 0);
exports.CommandOptions = CommandOptions;
let default_1 = class default_1 extends profile_command_1.ProfileCommand {
    constructor() {
        super();
    }
    async execute(options) {
        this.options = options;
        this.profile = this.getProfile(this.options);
        const txInputType = await new transactionInputType_resolver_1.TransactionInputTypeResolver().resolve(options);
        if (txInputType === transactionInputType_resolver_1.TransactionInputType.HASH) {
            const repositoryFactory = this.profile.repositoryFactory;
            const transactionHttp = repositoryFactory.createTransactionRepository();
            const hash = await new hash_resolver_1.HashResolver().resolve(options, 'Enter the hash of the aggregate bonded transaction to cosign: ');
            this.spinner.start();
            transactionHttp.getTransaction(hash, symbol_sdk_1.TransactionGroup.Partial).subscribe(async (transaction) => {
                this.spinner.stop();
                console.log(formatter_service_1.FormatterService.title('Transaction to cosign:'));
                new transaction_view_1.TransactionView(transaction, undefined, this.profile).print();
                const cosignedTransaction = await this.getSignedAggregateBondedCosignature(transaction, hash);
                if (cosignedTransaction) {
                    this.announceAggregateBondedCosignature(cosignedTransaction);
                }
            }, (err) => {
                this.spinner.stop();
                console.log(formatter_service_1.FormatterService.error(err));
            });
        }
        else {
            // tx payload selected
            const txPayload = await (0, options_resolver_1.OptionsResolver)(options, 'payload', () => undefined, 'Enter the transaction payload (hex string):', 'text', undefined);
            const transaction = symbol_sdk_1.TransactionMapping.createFromPayload(txPayload);
            console.log(formatter_service_1.FormatterService.success('Transaction to cosign:'));
            new transaction_view_1.TransactionView(transaction, undefined, this.profile).print();
            const cosignedTransaction = await this.getSignedAggregatePayloadCosignature(transaction, txPayload);
            if (cosignedTransaction) {
                console.log('Co-signed transaction:' + JSON.stringify(cosignedTransaction));
            }
        }
    }
    /**
     * Attempts to cosign an aggregated transaction with transaction payload (off chain)
     * @private
     * @param transaction the transaction
     * @param {string} payload of the transaction to be cosigned
     * @returns {(CosignatureSignedTransaction | null)}
     */
    async getSignedAggregatePayloadCosignature(transaction, payload) {
        const account = await this.profile.getSigningAccount(() => new password_resolver_1.PasswordResolver().resolve(this.options));
        try {
            const hash = symbol_sdk_1.Transaction.createTransactionHash(payload, Array.from(symbol_sdk_1.Convert.hexToUint8(this.profile.networkGenerationHash)));
            const signature = await account.cosignTransaction(transaction, hash);
            return new symbol_sdk_1.CosignatureSignedTransaction(hash, signature, account.publicKey);
        }
        catch (err) {
            this.spinner.stop();
            console.log(formatter_service_1.FormatterService.error(`The profile ${this.profile.name} cannot cosign the transaction with payload ${payload}.  Error: ${err.message || 'Unknown'}`));
            return null;
        }
        finally {
            await account.close();
        }
    }
    /**
     * Attempts to cosign an aggregated transaction cosignature
     * @private
     * @param {AggregateTransaction} transaction
     * @param {string} hash of the transaction to be cosigned
     * @returns {(CosignatureSignedTransaction | null)}
     */
    async getSignedAggregateBondedCosignature(transaction, hash) {
        const account = await this.profile.getSigningAccount(() => new password_resolver_1.PasswordResolver().resolve(this.options));
        try {
            const signature = await account.cosignTransaction(transaction, hash);
            return new symbol_sdk_1.CosignatureSignedTransaction(hash, signature, account.publicKey);
        }
        catch (err) {
            console.log(formatter_service_1.FormatterService.error(`The profile ${this.profile.name} cannot cosign the transaction with hash ${hash}. Error: ${err.message || 'Unknown'}`));
            return null;
        }
        finally {
            await account.close();
        }
    }
    /**
     * Announces aggregate bonded cosignature
     * @private
     * @param {CosignatureSignedTransaction} signedCosignature
     * @returns {Promise<void>}
     */
    async announceAggregateBondedCosignature(signedCosignature) {
        try {
            this.spinner.start();
            await this.profile.repositoryFactory
                .createTransactionRepository()
                .announceAggregateBondedCosignature(signedCosignature)
                .toPromise();
            this.spinner.stop();
            console.log(formatter_service_1.FormatterService.success('Transaction cosigned and announced correctly'));
        }
        catch (err) {
            this.spinner.stop();
            console.log(formatter_service_1.FormatterService.error(err));
        }
    }
};
__decorate([
    clime_1.metadata,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CommandOptions]),
    __metadata("design:returntype", Promise)
], default_1.prototype, "execute", null);
default_1 = __decorate([
    (0, clime_1.command)({
        description: 'Cosign an aggregate bonded transaction',
    }),
    __metadata("design:paramtypes", [])
], default_1);
exports.default = default_1;
