// 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);
};
import { SetVotingRightsCommand } from "../../../app/usecase/command/equity/votingRights/set/SetVotingRightsCommand";
import { CancelVotingCommand } from "../../../app/usecase/command/equity/votingRights/cancel/CancelVotingCommand";
import { GetVotingQuery } from "../../../app/usecase/query/equity/votingRights/getVoting/GetVotingQuery";
import { GetVotingCountQuery } from "../../../app/usecase/query/equity/votingRights/getVotingCount/GetVotingCountQuery";
import { GetVotingForQuery } from "../../../app/usecase/query/equity/votingRights/getVotingFor/GetVotingForQuery";
import { CancelScheduledBalanceAdjustmentCommand } from "../../../app/usecase/command/equity/balanceAdjustments/cancelScheduledBalanceAdjustment/CancelScheduledBalanceAdjustmentCommand";
import { SetScheduledBalanceAdjustmentCommand } from "../../../app/usecase/command/equity/balanceAdjustments/setScheduledBalanceAdjustment/SetScheduledBalanceAdjustmentCommand";
import Injectable from "../../../core/injectable/Injectable";
import { CommandBus } from "../../../core/command/CommandBus";
import { LogError } from "../../../core/decorator/LogErrorDecorator";
import { QueryBus } from "../../../core/query/QueryBus";
import { ONE_THOUSAND } from "../../../domain/context/shared/SecurityDate";
import ValidatedRequest from "../../../core/validation/ValidatedArgs";
import SetVotingRightsRequest from "../request/equity/SetVotingRightsRequest";
import GetVotingRightsForRequest from "../request/equity/GetVotingRightsForRequest";
import GetVotingRightsRequest from "../request/equity/GetVotingRightsRequest";
import GetAllVotingRightsRequest from "../request/equity/GetAllVotingRightsRequest";
import CreateEquityRequest from "../request/equity/CreateEquityRequest";
import NetworkService from "../../../app/service/network/NetworkService";
import { CreateEquityCommand } from "../../../app/usecase/command/equity/create/CreateEquityCommand";
import ContractId from "../../../domain/context/contract/ContractId";
import { GetSecurityQuery } from "../../../app/usecase/query/security/get/GetSecurityQuery";
import { CastDividendType } from "../../../domain/context/equity/DividendType";
import BigDecimal from "../../../domain/context/shared/BigDecimal";
import GetEquityDetailsRequest from "../request/equity/GetEquityDetailsRequest";
import { GetEquityDetailsQuery } from "../../../app/usecase/query/equity/get/getEquityDetails/GetEquityDetailsQuery";
import { CastRegulationSubType, CastRegulationType } from "../../../domain/context/factory/RegulationType";
import CancelScheduledBalanceAdjustmentRequest from "../request/equity/CancelScheduledBalanceAdjustmentRequest";
import SetScheduledBalanceAdjustmentRequest from "../request/equity/SetScheduledBalanceAdjustmentRequest";
import GetScheduledBalanceAdjustmentRequest from "../request/equity/GetScheduledBalanceAdjustmentRequest";
import { GetScheduledBalanceAdjustmentQuery } from "../../../app/usecase/query/equity/balanceAdjustments/getScheduledBalanceAdjustment/GetScheduledBalanceAdjustmentQuery";
import GetScheduledBalanceAdjustmentCountRequest from "../request/equity/GetScheduledBalanceAdjustmentsCountRequest";
import { GetScheduledBalanceAdjustmentCountQuery } from "../../../app/usecase/query/equity/balanceAdjustments/getScheduledBalanceAdjustmentCount/GetScheduledBalanceAdjustmentsCountQuery";
import { GetVotingHoldersQuery } from "../../../app/usecase/query/equity/votingRights/getVotingHolders/GetVotingHoldersQuery";
import { GetTotalVotingHoldersQuery } from "../../../app/usecase/query/equity/votingRights/getTotalVotingHolders/GetTotalVotingHoldersQuery";
import GetAllScheduledBalanceAdjustmentsRequest from "../request/equity/GetAllScheduledBalanceAdjustmentst";
import GetVotingHoldersRequest from "../request/equity/GetVotingHoldersRequest";
import GetTotalVotingHoldersRequest from "../request/equity/GetTotalVotingHoldersRequest";
import CreateTrexSuiteEquityRequest from "../request/equity/CreateTrexSuiteEquityRequest";
import { CreateTrexSuiteEquityCommand } from "../../../app/usecase/command/equity/createTrexSuite/CreateTrexSuiteEquityCommand";
import CancelVotingRequest from "../request/equity/CancelVotingRequest";
class EquityInPort {
    queryBus;
    commandBus;
    networkService;
    constructor(queryBus = Injectable.resolve(QueryBus), commandBus = Injectable.resolve(CommandBus), networkService = Injectable.resolve(NetworkService)) {
        this.queryBus = queryBus;
        this.commandBus = commandBus;
        this.networkService = networkService;
    }
    async createTrexSuite(req) {
        ValidatedRequest.handleValidation("CreateTrexSuiteEquityRequest", req);
        const { diamondOwnerAccount, externalPauses, externalControlLists, externalKycLists } = req;
        const securityFactory = this.networkService.configuration.factoryAddress;
        const resolver = this.networkService.configuration.resolverAddress;
        const newSecurity = {
            name: req.name,
            symbol: req.symbol,
            isin: req.isin,
            decimals: req.decimals,
            isWhiteList: req.isWhiteList,
            isControllable: req.isControllable,
            arePartitionsProtected: req.arePartitionsProtected,
            clearingActive: req.clearingActive,
            internalKycActivated: req.internalKycActivated,
            isMultiPartition: req.isMultiPartition,
            maxSupply: BigDecimal.fromString(req.numberOfShares),
            regulationType: CastRegulationType.fromNumber(req.regulationType),
            regulationsubType: CastRegulationSubType.fromNumber(req.regulationSubType),
            isCountryControlListWhiteList: req.isCountryControlListWhiteList,
            countries: req.countries,
            info: req.info,
            erc20VotesActivated: req.erc20VotesActivated,
        };
        const createResponse = await this.commandBus.execute(new CreateTrexSuiteEquityCommand(req.salt, req.owner, req.irs, req.onchainId, req.irAgents, req.tokenAgents, req.compliancesModules, req.complianceSettings, req.claimTopics, req.issuers, req.issuerClaims, newSecurity, req.votingRight, req.informationRight, req.liquidationRight, req.subscriptionRight, req.conversionRight, req.redemptionRight, req.putRight, CastDividendType.fromNumber(req.dividendRight), req.currency, req.nominalValue, req.nominalValueDecimals, new ContractId(securityFactory), new ContractId(resolver), req.configId, req.configVersion, diamondOwnerAccount, externalPauses, externalControlLists, externalKycLists, req.complianceId, req.identityRegistryId));
        const securityCreated = createResponse.securityId.toString() !== ContractId.NULL.toString();
        const res = securityCreated
            ? (await this.queryBus.execute(new GetSecurityQuery(createResponse.securityId.toString()))).security
            : {};
        return {
            security: securityCreated
                ? {
                    ...res,
                }
                : {},
            transactionId: createResponse.transactionId,
        };
    }
    async create(req) {
        ValidatedRequest.handleValidation("CreateEquityRequest", req);
        const { diamondOwnerAccount, externalPausesIds, externalControlListsIds, externalKycListsIds } = req;
        const securityFactory = this.networkService.configuration.factoryAddress;
        const resolver = this.networkService.configuration.resolverAddress;
        const newSecurity = {
            name: req.name,
            symbol: req.symbol,
            isin: req.isin,
            decimals: req.decimals,
            isWhiteList: req.isWhiteList,
            erc20VotesActivated: req.erc20VotesActivated,
            isControllable: req.isControllable,
            arePartitionsProtected: req.arePartitionsProtected,
            clearingActive: req.clearingActive,
            internalKycActivated: req.internalKycActivated,
            isMultiPartition: req.isMultiPartition,
            maxSupply: BigDecimal.fromString(req.numberOfShares),
            regulationType: CastRegulationType.fromNumber(req.regulationType),
            regulationsubType: CastRegulationSubType.fromNumber(req.regulationSubType),
            isCountryControlListWhiteList: req.isCountryControlListWhiteList,
            countries: req.countries,
            info: req.info,
        };
        const createResponse = await this.commandBus.execute(new CreateEquityCommand(newSecurity, req.votingRight, req.informationRight, req.liquidationRight, req.subscriptionRight, req.conversionRight, req.redemptionRight, req.putRight, CastDividendType.fromNumber(req.dividendRight), req.currency, req.nominalValue, req.nominalValueDecimals, securityFactory ? new ContractId(securityFactory) : undefined, resolver ? new ContractId(resolver) : undefined, req.configId, req.configVersion, diamondOwnerAccount, externalPausesIds, externalControlListsIds, externalKycListsIds, req.complianceId, req.identityRegistryId));
        const securityCreated = createResponse.securityId.toString() !== ContractId.NULL.toString();
        const res = securityCreated
            ? (await this.queryBus.execute(new GetSecurityQuery(createResponse.securityId.toString()))).security
            : {};
        return {
            security: securityCreated
                ? {
                    ...res,
                }
                : {},
            transactionId: createResponse.transactionId,
        };
    }
    async getEquityDetails(request) {
        ValidatedRequest.handleValidation("GetEquityDetailsRequest", request);
        const res = await this.queryBus.execute(new GetEquityDetailsQuery(request.equityId));
        const equityDetails = {
            votingRight: res.equity.votingRight,
            informationRight: res.equity.informationRight,
            liquidationRight: res.equity.liquidationRight,
            subscriptionRight: res.equity.subscriptionRight,
            conversionRight: res.equity.conversionRight,
            redemptionRight: res.equity.redemptionRight,
            putRight: res.equity.putRight,
            dividendRight: CastDividendType.toNumber(res.equity.dividendRight),
            currency: res.equity.currency,
            nominalValue: res.equity.nominalValue.toString(),
            nominalValueDecimals: res.equity.nominalValueDecimals,
        };
        return equityDetails;
    }
    async setVotingRights(request) {
        const { recordTimestamp, securityId, data } = request;
        ValidatedRequest.handleValidation("SetVotingRightsRequest", request);
        return await this.commandBus.execute(new SetVotingRightsCommand(securityId, recordTimestamp, data));
    }
    async cancelVoting(request) {
        const { securityId, votingId } = request;
        ValidatedRequest.handleValidation("CancelVotingRequest", request);
        return await this.commandBus.execute(new CancelVotingCommand(securityId, votingId));
    }
    async getVotingRightsFor(request) {
        ValidatedRequest.handleValidation("GetVotingRightsForRequest", request);
        const res = await this.queryBus.execute(new GetVotingForQuery(request.targetId, request.securityId, request.votingId));
        const votingFor = {
            tokenBalance: res.tokenBalance.toString(),
            decimals: res.decimals.toString(),
            isDisabled: res.isDisabled,
        };
        return votingFor;
    }
    async getVotingRights(request) {
        ValidatedRequest.handleValidation("GetVotingRightsRequest", request);
        const res = await this.queryBus.execute(new GetVotingQuery(request.securityId, request.votingId));
        const votingRight = {
            votingId: request.votingId,
            recordDate: new Date(res.voting.recordTimeStamp * ONE_THOUSAND),
            data: res.voting.data,
            isDisabled: res.voting.isDisabled,
        };
        return votingRight;
    }
    async getAllVotingRights(request) {
        ValidatedRequest.handleValidation("GetAllVotingRightsRequest", request);
        const count = await this.queryBus.execute(new GetVotingCountQuery(request.securityId));
        if (count.payload == 0)
            return [];
        const votingRights = [];
        for (let i = 1; i <= count.payload; i++) {
            const res = await this.queryBus.execute(new GetVotingQuery(request.securityId, i));
            const votingright = {
                votingId: i,
                recordDate: new Date(res.voting.recordTimeStamp * ONE_THOUSAND),
                data: res.voting.data,
                isDisabled: res.voting.isDisabled,
            };
            votingRights.push(votingright);
        }
        return votingRights;
    }
    async setScheduledBalanceAdjustment(request) {
        const { executionDate, factor, decimals, securityId } = request;
        ValidatedRequest.handleValidation("SetScheduledBalanceAdjustmentRequest", request);
        return await this.commandBus.execute(new SetScheduledBalanceAdjustmentCommand(securityId, executionDate, factor, decimals));
    }
    async getScheduledBalanceAdjustment(request) {
        ValidatedRequest.handleValidation("GetScheduledBalanceAdjustmentRequest", request);
        const res = await this.queryBus.execute(new GetScheduledBalanceAdjustmentQuery(request.securityId, request.balanceAdjustmentId));
        const scheduledBalanceAdjustment = {
            id: request.balanceAdjustmentId,
            executionDate: new Date(res.scheduleBalanceAdjustment.executionTimeStamp * ONE_THOUSAND),
            factor: res.scheduleBalanceAdjustment.factor.toString(),
            decimals: res.scheduleBalanceAdjustment.decimals.toString(),
            isDisabled: res.scheduleBalanceAdjustment.isDisabled,
        };
        return scheduledBalanceAdjustment;
    }
    async getScheduledBalanceAdjustmentsCount(request) {
        const { securityId } = request;
        ValidatedRequest.handleValidation("GetScheduledBalanceAdjustmentCountRequest", request);
        const getScheduledBalanceAdjustmentCountQueryResponse = await this.queryBus.execute(new GetScheduledBalanceAdjustmentCountQuery(securityId));
        return getScheduledBalanceAdjustmentCountQueryResponse.payload;
    }
    async getAllScheduledBalanceAdjustments(request) {
        ValidatedRequest.handleValidation("GetAllScheduledBalanceAdjustmentsRequest", request);
        const count = await this.queryBus.execute(new GetScheduledBalanceAdjustmentCountQuery(request.securityId));
        if (count.payload == 0)
            return [];
        const scheduledBalanceAdjustments = [];
        for (let i = 1; i <= count.payload; i++) {
            const res = await this.queryBus.execute(new GetScheduledBalanceAdjustmentQuery(request.securityId, i));
            const scheduledBalanceAdjustment = {
                id: i,
                executionDate: new Date(res.scheduleBalanceAdjustment.executionTimeStamp * ONE_THOUSAND),
                factor: res.scheduleBalanceAdjustment.factor.toString(),
                decimals: res.scheduleBalanceAdjustment.decimals.toString(),
                isDisabled: res.scheduleBalanceAdjustment.isDisabled,
            };
            scheduledBalanceAdjustments.push(scheduledBalanceAdjustment);
        }
        return scheduledBalanceAdjustments;
    }
    async getVotingHolders(request) {
        const { securityId, voteId, start, end } = request;
        ValidatedRequest.handleValidation(GetVotingHoldersRequest.name, request);
        return (await this.queryBus.execute(new GetVotingHoldersQuery(securityId, voteId, start, end))).payload;
    }
    async getTotalVotingHolders(request) {
        const { securityId, voteId } = request;
        ValidatedRequest.handleValidation(GetTotalVotingHoldersRequest.name, request);
        return (await this.queryBus.execute(new GetTotalVotingHoldersQuery(securityId, voteId))).payload;
    }
    async cancelScheduledBalanceAdjustment(request) {
        const { securityId, balanceAdjustmentId } = request;
        ValidatedRequest.handleValidation("CancelScheduledBalanceAdjustmentRequest", request);
        return await this.commandBus.execute(new CancelScheduledBalanceAdjustmentCommand(securityId, balanceAdjustmentId));
    }
}
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CreateTrexSuiteEquityRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "createTrexSuite", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CreateEquityRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "create", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetEquityDetailsRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getEquityDetails", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [SetVotingRightsRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "setVotingRights", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CancelVotingRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "cancelVoting", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetVotingRightsForRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getVotingRightsFor", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetVotingRightsRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getVotingRights", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetAllVotingRightsRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getAllVotingRights", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [SetScheduledBalanceAdjustmentRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "setScheduledBalanceAdjustment", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetScheduledBalanceAdjustmentRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getScheduledBalanceAdjustment", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetScheduledBalanceAdjustmentCountRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getScheduledBalanceAdjustmentsCount", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetAllScheduledBalanceAdjustmentsRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getAllScheduledBalanceAdjustments", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetVotingHoldersRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getVotingHolders", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [GetTotalVotingHoldersRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "getTotalVotingHolders", null);
__decorate([
    LogError,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CancelScheduledBalanceAdjustmentRequest]),
    __metadata("design:returntype", Promise)
], EquityInPort.prototype, "cancelScheduledBalanceAdjustment", null);
const EquityToken = new EquityInPort();
export default EquityToken;
