"use strict";
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
Object.defineProperty(exports, "__esModule", { value: true });
const operators_1 = require("rxjs/operators");
const types_1 = require("../../types");
const util_1 = require("../util");
const util_2 = require("./util");
class Contract extends util_2.BaseWithTxAndRpcCall {
    constructor(api, abi, decorateMethod, address) {
        super(api, abi, decorateMethod);
        this.address = types_1.createType(this.registry, 'Address', address);
    }
    call(as, message, value, gasLimit, ...params) {
        const { fn, def } = this.getMessage(message);
        return {
            send: this.decorateMethod(as === 'rpc' && this.hasRpcContractsCall
                ? (account) => {
                    return this.rpcContractsCall(types_1.createType(this.registry, 'ContractCallRequest', {
                        origin: account,
                        dest: this.address.toString(),
                        value,
                        gasLimit,
                        inputData: fn(...params)
                    }))
                        .pipe(operators_1.map((result) => this.createOutcome(result, types_1.createType(this.registry, 'AccountId', account), def, params)));
                }
                : (account) => {
                    return this.apiContracts
                        .call(this.address, value, gasLimit, fn(...params))
                        .signAndSend(account);
                })
        };
    }
    createOutcome(result, origin, message, params) {
        let output = null;
        if (result.isSuccess) {
            const { data } = result.asSuccess;
            output = message.returnType
                ? util_1.formatData(this.registry, data, message.returnType)
                : types_1.createType(this.registry, 'Raw', data);
        }
        return {
            time: Date.now(),
            message,
            origin,
            params,
            result,
            isSuccess: result.isSuccess,
            output
        };
    }
}
exports.default = Contract;
