// SPDX-License-Identifier: Apache-2.0
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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { Client } from "@hiero-ledger/sdk";
import { SignatureRequest } from "@hashgraph/hedera-custodians-integration";
import Account from "../../../../domain/context/account/Account";
import { lazyInject } from "../../../../core/decorator/LazyInjectDecorator";
import EventService from "../../../../app/service/event/EventService";
import { MirrorNodeAdapter } from "../../../out/mirror/MirrorNodeAdapter";
import NetworkService from "../../../../app/service/network/NetworkService";
import LogService from "../../../../app/service/log/LogService";
import { SigningError } from "../../../out/error/SigningError";
import { WalletEvents } from "../../../../app/service/event/WalletEvent";
import Injectable from "../../../../core/injectable/Injectable";
import Hex from "../../../../core/Hex";
import { BaseHederaTransactionAdapter } from "../../../out/hs/BaseHederaTransactionAdapter";
import { HTSTransactionResponseAdapter } from "../../../out/response/HTSTransactionResponseAdapter";
import { HederaId } from "../../../../domain/context/shared/HederaId";
import { PublickKeyNotFound } from "./error/PublickKeyNotFound";
import { UnsupportedNetwork } from "../../../../domain/context/network/error/UnsupportedNetwork";
let CustodialTransactionAdapter = class CustodialTransactionAdapter extends BaseHederaTransactionAdapter {
    eventService;
    mirrorNodeAdapter;
    networkService;
    client;
    custodialWalletService;
    account;
    network;
    constructor(eventService, mirrorNodeAdapter, networkService) {
        super(mirrorNodeAdapter, networkService);
        this.eventService = eventService;
        this.mirrorNodeAdapter = mirrorNodeAdapter;
        this.networkService = networkService;
    }
    initClient(accountId, publicKey) {
        const currentNetwork = this.networkService.environment;
        switch (currentNetwork) {
            case "testnet":
                this.client = Client.forTestnet();
                break;
            case "mainnet":
                this.client = Client.forMainnet();
                break;
            case "previewnet":
                this.client = Client.forPreviewnet();
                break;
            default:
                throw new UnsupportedNetwork();
        }
        this.client.setOperatorWith(accountId, publicKey, this.signingService);
    }
    signingService = async (message) => {
        const signatureRequest = new SignatureRequest(message);
        return await this.custodialWalletService.signTransaction(signatureRequest);
    };
    async processTransaction(transaction, transactionType, 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    _startDate) {
        try {
            const txResponse = await transaction.execute(this.client);
            this.logTransaction(txResponse.transactionId.toString(), this.networkService.environment);
            return HTSTransactionResponseAdapter.manageResponse(this.networkService.environment, txResponse, transactionType, this.client);
        }
        catch (error) {
            LogService.logError(error);
            throw new SigningError(error);
        }
    }
    supportsEvmOperations() {
        return false;
    }
    createWalletPairedEvent(wallet) {
        return {
            wallet: wallet,
            data: {
                account: this.account,
                pairing: "",
                topic: "",
            },
            network: {
                name: this.networkService.environment,
                recognized: true,
                factoryId: this.networkService.configuration?.factoryAddress ?? "",
            },
        };
    }
    async register(settings) {
        Injectable.registerTransactionHandler(this);
        const accountMirror = await this.mirrorNodeAdapter.getAccountInfo(new HederaId(settings.hederaAccountId));
        if (!accountMirror.publicKey) {
            throw new PublickKeyNotFound();
        }
        this.account = new Account({
            id: settings.hederaAccountId,
            evmAddress: accountMirror.evmAddress,
            publicKey: accountMirror.publicKey,
        });
        this.initCustodialWalletService(settings);
        this.initClient(settings.hederaAccountId, accountMirror.publicKey.key);
        const wallet = this.getSupportedWallet();
        const eventData = this.createWalletPairedEvent(wallet);
        this.eventService.emit(WalletEvents.walletPaired, eventData);
        LogService.logTrace(`${wallet} registered as handler: `, eventData);
        return { account: this.getAccount() };
    }
    getAccount() {
        return this.account;
    }
    async sign(message) {
        if (!this.custodialWalletService)
            throw new SigningError("Custodial Wallet is empty");
        try {
            const encoded_message = Hex.toUint8Array(message);
            const encoded_signed_message = await this.signingService(encoded_message);
            const hexArray = Array.from(encoded_signed_message, (byte) => ("0" + byte.toString(16)).slice(-2));
            return hexArray.join("");
        }
        catch (error) {
            LogService.logError(error);
            throw new SigningError(error);
        }
    }
};
CustodialTransactionAdapter = __decorate([
    __param(0, lazyInject(EventService)),
    __param(1, lazyInject(MirrorNodeAdapter)),
    __param(2, lazyInject(NetworkService)),
    __metadata("design:paramtypes", [EventService,
        MirrorNodeAdapter,
        NetworkService])
], CustodialTransactionAdapter);
export { CustodialTransactionAdapter };
