"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PowerPlantMutation = void 0;
const tslib_1 = require("tslib");
const type_graphql_1 = require("type-graphql");
const typeorm_1 = require("typeorm");
const shell_1 = require("@things-factory/shell");
const finalize_data_collection_1 = require("@things-factory/dataset/dist-server/controllers/finalize-data-collection");
const inverter_1 = require("@esome-dev/inverter");
const power_plant_type_1 = require("./power-plant-type");
const integration_base_1 = require("@things-factory/integration-base");
const power_plant_query_1 = require("./power-plant-query");
const DATA_SET_ID = 'ff17350e-ab0c-403c-8894-767465e8e971'; // 인버터 데이터셋
let PowerPlantMutation = class PowerPlantMutation {
    async hourSummaryAllPowerPlant(context) {
        const { tx } = context.state;
        const powerPlants = await tx.getRepository(shell_1.Domain).find({
            where: { extType: (0, typeorm_1.In)(['power-plant', 'all-power-plant', 'sunflow-power-plant']) }
        });
        for (const powerPlant of powerPlants) {
            context.state.domain = powerPlant;
            await (0, finalize_data_collection_1.finalizeLatestDataCollection)(DATA_SET_ID, context);
        }
        return true;
    }
    async resetAllInverterStatuses(context) {
        const { tx } = context.state;
        // 모든 inverter status 초기화
        await tx
            .getRepository(inverter_1.InverterStatus)
            .createQueryBuilder()
            .update(inverter_1.InverterStatus)
            .set({
            acc: 0,
            ac: 0,
            ds: 0,
            dc: 0,
            run: '0',
            com: '1'
        })
            .execute();
        return true;
    }
    // 파워플래너 ID/PW 업데이트 시 커넥션 업데이트 및 없으면 자동 생성
    async updateSunflowConnections(patches, context) {
        const { tx, user } = context.state;
        const connRepository = tx.getRepository(integration_base_1.Connection);
        for (const patch of patches) {
            // 배출권 시장 커넥션 없으면 생성 (전부 고정된 값)
            if (!patch.emissionMarketConnectionId) {
                await connRepository.save({
                    name: power_plant_query_1.EMISSION_MARKET_CONNECTION_NAME,
                    description: '배출권시장 정보플랫폼',
                    active: true,
                    onDemand: false,
                    type: 'headless-connector',
                    endpoint: 'https://ets.krx.co.kr',
                    domain: { id: patch.id },
                    creator: user,
                    updater: user
                });
            }
            // 파워 플래너 커넥션 없으면 생성 (전부 고정된 값)
            if (!patch.powerPlannerConnectionId) {
                await connRepository.save({
                    name: power_plant_query_1.POWER_PLANNER_CONNECTION_NAME,
                    description: '한전 파워플래너',
                    active: true,
                    onDemand: false,
                    type: 'headless-connector',
                    endpoint: 'https://pp.kepco.co.kr',
                    params: {
                        username: patch?.kepcoId || '',
                        password: patch?.kepcoPassword || '',
                        loginPagePath: '/intro.do',
                        loginApiUrl: '/login',
                        usernameSelector: '#RSA_USER_ID',
                        passwordSelector: '#RSA_USER_PWD',
                        submitSelector: 'input.intro_btn',
                        successSelector: '',
                        shadowDomSelectors: '',
                        timeout: 15000,
                        retries: 3
                    },
                    domain: { id: patch.id },
                    creator: user,
                    updater: user
                });
            }
            else {
                // 파워 플래너 커넥션 있으면 업데이트
                const oldConnection = await connRepository.findOne({ where: { id: patch.powerPlannerConnectionId } });
                let params = oldConnection.params;
                params.username = patch.kepcoId || params.username;
                params.password = patch.kepcoPassword || params.password;
                await connRepository.save({ ...oldConnection, params: params, updater: user });
            }
        }
        return true;
    }
    // sunflow 어드민에서 커넥션 연결용 리졸버
    async connectPowerPlantConnection(name, domainId, context) {
        const { tx } = context.state;
        const domainRepo = tx.getRepository(shell_1.Domain);
        const target = await domainRepo.findOne({ where: { id: domainId } });
        if (!target)
            return false;
        context.state.domain = target;
        const connectionRepo = tx.getRepository(integration_base_1.Connection);
        let connection = await connectionRepo.findOne({
            where: { domain: { id: target.id }, name },
            relations: ['domain', 'edge']
        });
        if (!connection)
            return false;
        if (connection.domain.id !== target.id) {
            connection.domain = target;
            await connection.connect();
        }
        else {
            await connection.connect();
            await connectionRepo.save(connection);
        }
        return true;
    }
    // sunflow 어드민에서 커넥션 연결용 리졸버
    async disconnectPowerPlantConnection(name, domainId, context) {
        const { tx } = context.state;
        const domainRepo = tx.getRepository(shell_1.Domain);
        const target = await domainRepo.findOne({ where: { id: domainId } });
        if (!target)
            return false;
        const connectionRepo = tx.getRepository(integration_base_1.Connection);
        let connection = await connectionRepo.findOne({
            where: { domain: { id: target.id }, name },
            relations: ['domain', 'edge']
        });
        if (!connection)
            return false;
        if (connection.domain.id !== target.id) {
            connection.domain = target;
            await connection.disconnect();
        }
        else {
            await connection.disconnect();
            await connectionRepo.save(connection);
        }
        return true;
    }
};
exports.PowerPlantMutation = PowerPlantMutation;
tslib_1.__decorate([
    (0, type_graphql_1.Directive)('@transaction'),
    (0, type_graphql_1.Mutation)(returns => Boolean, { description: 'To finalize new Data Summaries' }),
    tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantMutation.prototype, "hourSummaryAllPowerPlant", null);
tslib_1.__decorate([
    (0, type_graphql_1.Directive)('@transaction'),
    (0, type_graphql_1.Mutation)(returns => Boolean, { description: 'To reset all inverter statuses' }),
    tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantMutation.prototype, "resetAllInverterStatuses", null);
tslib_1.__decorate([
    (0, type_graphql_1.Directive)('@transaction'),
    (0, type_graphql_1.Mutation)(returns => Boolean, { description: 'To update sunflow power plant connections' }),
    tslib_1.__param(0, (0, type_graphql_1.Arg)('patches', type => [power_plant_type_1.SunflowConnectionPatch])),
    tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Array, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantMutation.prototype, "updateSunflowConnections", null);
tslib_1.__decorate([
    (0, type_graphql_1.Directive)('@transaction'),
    (0, type_graphql_1.Mutation)(returns => Boolean, { description: 'Connect a specified connection for a single domain.' }),
    tslib_1.__param(0, (0, type_graphql_1.Arg)('name')),
    tslib_1.__param(1, (0, type_graphql_1.Arg)('domainId')),
    tslib_1.__param(2, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [String, String, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantMutation.prototype, "connectPowerPlantConnection", null);
tslib_1.__decorate([
    (0, type_graphql_1.Directive)('@transaction'),
    (0, type_graphql_1.Mutation)(returns => Boolean, { description: 'Disconnect a specified connection for a single domain.' }),
    tslib_1.__param(0, (0, type_graphql_1.Arg)('name')),
    tslib_1.__param(1, (0, type_graphql_1.Arg)('domainId')),
    tslib_1.__param(2, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [String, String, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantMutation.prototype, "disconnectPowerPlantConnection", null);
exports.PowerPlantMutation = PowerPlantMutation = tslib_1.__decorate([
    (0, type_graphql_1.Resolver)(shell_1.Domain)
], PowerPlantMutation);
//# sourceMappingURL=power-plant-mutation.js.map