"use strict";
// SPDX-License-Identifier: Apache-2.0
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SupportedWallets = void 0;
/* eslint-disable @typescript-eslint/no-unused-vars */
const Injectable_1 = __importDefault(require("../../../core/injectable/Injectable"));
const CommandBus_1 = require("../../../core/command/CommandBus");
const ConnectCommand_1 = require("../../../app/usecase/command/network/connect/ConnectCommand");
const ConnectRequest_1 = __importStar(require("../request/network/ConnectRequest"));
Object.defineProperty(exports, "SupportedWallets", { enumerable: true, get: function () { return ConnectRequest_1.SupportedWallets; } });
const RequestMapper_1 = __importDefault(require("../request/mapping/RequestMapper"));
const TransactionService_1 = __importDefault(require("../../../app/service/transaction/TransactionService"));
const NetworkService_1 = __importDefault(require("../../../app/service/network/NetworkService"));
const SetNetworkRequest_1 = __importDefault(require("../request/network/SetNetworkRequest"));
const SetNetworkCommand_1 = require("../../../app/usecase/command/network/setNetwork/SetNetworkCommand");
const SetConfigurationCommand_1 = require("../../../app/usecase/command/network/setConfiguration/SetConfigurationCommand");
const Environment_1 = require("../../../domain/context/network/Environment");
const InitializationRequest_1 = __importDefault(require("../request/network/InitializationRequest"));
const Event_1 = __importDefault(require("../event/Event"));
const RPCTransactionAdapter_1 = require("../../out/rpc/RPCTransactionAdapter");
const LogErrorDecorator_1 = require("../../../core/decorator/LogErrorDecorator");
const SetConfigurationRequest_1 = __importDefault(require("../request/management/SetConfigurationRequest"));
const ValidatedArgs_1 = __importDefault(require("../../../core/validation/ValidatedArgs"));
const HederaWalletConnectTransactionAdapter_1 = require("../../out/hs/walletconnect/HederaWalletConnectTransactionAdapter");
const DFNSTransactionAdapter_1 = require("../../out/hs/custodial/DFNSTransactionAdapter");
const FireblocksTransactionAdapter_1 = require("../../out/hs/custodial/FireblocksTransactionAdapter");
const AWSKMSTransactionAdapter_1 = require("../../out/hs/custodial/AWSKMSTransactionAdapter");
const LogService_1 = __importDefault(require("../../../app/service/log/LogService"));
class NetworkInPort {
    commandBus;
    transactionService;
    networkService;
    constructor(commandBus = Injectable_1.default.resolve(CommandBus_1.CommandBus), transactionService = Injectable_1.default.resolve(TransactionService_1.default), networkService = Injectable_1.default.resolve(NetworkService_1.default)) {
        this.commandBus = commandBus;
        this.transactionService = transactionService;
        this.networkService = networkService;
    }
    async setConfig(req) {
        ValidatedArgs_1.default.handleValidation("SetConfigurationRequest", req);
        const res = await this.commandBus.execute(new SetConfigurationCommand_1.SetConfigurationCommand(req.factoryAddress, req.resolverAddress));
        return res;
    }
    getFactoryAddress() {
        return this.networkService.configuration ? this.networkService.configuration.factoryAddress : "";
    }
    getResolverAddress() {
        return this.networkService.configuration ? this.networkService.configuration.resolverAddress : "";
    }
    getNetwork() {
        return this.networkService.environment;
    }
    isNetworkRecognized() {
        return this.networkService.environment != Environment_1.unrecognized;
    }
    async setNetwork(req) {
        ValidatedArgs_1.default.handleValidation("SetNetworkRequest", req);
        const res = await this.commandBus.execute(new SetNetworkCommand_1.SetNetworkCommand(req.environment, req.mirrorNode, req.rpcNode, req.consensusNodes));
        return res;
    }
    async init(req) {
        ValidatedArgs_1.default.handleValidation("InitializationRequest", req);
        await this.setNetwork(new SetNetworkRequest_1.default({
            environment: req.network,
            mirrorNode: req.mirrorNode,
            rpcNode: req.rpcNode,
        }));
        if (req.configuration)
            if (req.configuration.factoryAddress && req.configuration.resolverAddress)
                await this.setConfig(new SetConfigurationRequest_1.default({
                    factoryAddress: req.configuration.factoryAddress,
                    resolverAddress: req.configuration.resolverAddress,
                }));
        req.events && Event_1.default.register(req.events);
        const wallets = [];
        const instances = Injectable_1.default.registerTransactionAdapterInstances();
        for (const val of instances) {
            if (val instanceof RPCTransactionAdapter_1.RPCTransactionAdapter) {
                wallets.push(ConnectRequest_1.SupportedWallets.METAMASK);
            }
            else if (val instanceof HederaWalletConnectTransactionAdapter_1.HederaWalletConnectTransactionAdapter) {
                wallets.push(ConnectRequest_1.SupportedWallets.HWALLETCONNECT);
            }
            else if (val instanceof DFNSTransactionAdapter_1.DFNSTransactionAdapter) {
                wallets.push(ConnectRequest_1.SupportedWallets.DFNS);
            }
            else if (val instanceof FireblocksTransactionAdapter_1.FireblocksTransactionAdapter) {
                wallets.push(ConnectRequest_1.SupportedWallets.FIREBLOCKS);
            }
            else if (val instanceof AWSKMSTransactionAdapter_1.AWSKMSTransactionAdapter) {
                wallets.push(ConnectRequest_1.SupportedWallets.AWSKMS);
            }
            await val.init();
            if (val instanceof RPCTransactionAdapter_1.RPCTransactionAdapter) {
                val.setConfig({
                    mirrorNodes: req.mirrorNodes,
                    jsonRpcRelays: req.jsonRpcRelays,
                    factories: req.factories,
                    resolvers: req.resolvers,
                });
            }
        }
        return wallets;
    }
    async connect(req) {
        LogService_1.default.logInfo("ConnectRequest from network", req);
        ValidatedArgs_1.default.handleValidation("ConnectRequest", req);
        const account = req.account ? RequestMapper_1.default.mapAccount(req.account) : undefined;
        const debug = req.debug ?? false;
        const hwcSettings = req.hwcSettings ? RequestMapper_1.default.hwcRequestToHWCSettings(req.hwcSettings) : undefined;
        const custodialSettings = this.getCustodialSettings(req);
        LogService_1.default.logTrace("SetNetworkCommand", req.network, req.mirrorNode, req.rpcNode);
        await this.commandBus.execute(new SetNetworkCommand_1.SetNetworkCommand(req.network, req.mirrorNode, req.rpcNode));
        LogService_1.default.logTrace("ConnectRequest", req.wallet, account, hwcSettings, debug, custodialSettings);
        const res = await this.commandBus.execute(new ConnectCommand_1.ConnectCommand(req.network, req.wallet, account, hwcSettings, debug, custodialSettings));
        return res.payload;
    }
    getCustodialSettings(req) {
        if (!req.custodialWalletSettings) {
            return undefined;
        }
        switch (req.wallet) {
            case ConnectRequest_1.SupportedWallets.DFNS:
                return RequestMapper_1.default.dfnsRequestToDfnsSettings(req.custodialWalletSettings);
            case ConnectRequest_1.SupportedWallets.FIREBLOCKS:
                return RequestMapper_1.default.fireblocksRequestToFireblocksSettings(req.custodialWalletSettings);
            case ConnectRequest_1.SupportedWallets.AWSKMS:
                return RequestMapper_1.default.awsKmsRequestToAwsKmsSettings(req.custodialWalletSettings);
            default:
                return undefined;
        }
    }
    disconnect() {
        return this.transactionService.getHandler().stop();
    }
}
__decorate([
    LogErrorDecorator_1.LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [SetConfigurationRequest_1.default]),
    __metadata("design:returntype", Promise)
], NetworkInPort.prototype, "setConfig", null);
__decorate([
    LogErrorDecorator_1.LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", String)
], NetworkInPort.prototype, "getFactoryAddress", null);
__decorate([
    LogErrorDecorator_1.LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", String)
], NetworkInPort.prototype, "getResolverAddress", null);
__decorate([
    LogErrorDecorator_1.LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", String)
], NetworkInPort.prototype, "getNetwork", null);
__decorate([
    LogErrorDecorator_1.LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Boolean)
], NetworkInPort.prototype, "isNetworkRecognized", null);
__decorate([
    LogErrorDecorator_1.LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [SetNetworkRequest_1.default]),
    __metadata("design:returntype", Promise)
], NetworkInPort.prototype, "setNetwork", null);
__decorate([
    LogErrorDecorator_1.LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [InitializationRequest_1.default]),
    __metadata("design:returntype", Promise)
], NetworkInPort.prototype, "init", null);
__decorate([
    LogErrorDecorator_1.LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ConnectRequest_1.default]),
    __metadata("design:returntype", Promise)
], NetworkInPort.prototype, "connect", null);
const Network = new NetworkInPort();
exports.default = Network;
