"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PowerPlantQuery = exports.EMISSION_MARKET_CONNECTION_NAME = exports.POWER_PLANNER_CONNECTION_NAME = void 0;
const tslib_1 = require("tslib");
const type_graphql_1 = require("type-graphql");
const shell_1 = require("@things-factory/shell");
const typeorm_1 = require("typeorm");
const power_plant_type_1 = require("./power-plant-type");
const integration_base_1 = require("@things-factory/integration-base");
exports.POWER_PLANNER_CONNECTION_NAME = 'powerplanner';
exports.EMISSION_MARKET_CONNECTION_NAME = 'ets.krx.co.kr';
let PowerPlantQuery = class PowerPlantQuery {
    async powerPlants(params, context) {
        const { domain, user } = context.state;
        const descriptionFilter = params.filters.find(v => v.name === 'description');
        const queryBuilder = (0, shell_1.getRepository)(shell_1.Domain)
            .createQueryBuilder('child_d')
            .innerJoin('domains', 'parent_d', 'parent_d.id = child_d.parent_id')
            .innerJoin('users_domains', 'ud', 'parent_d.id = ud.domains_id')
            .where('ud.users_id = :userId', { userId: user.id })
            .orderBy('child_d.name', 'ASC');
        if (descriptionFilter) {
            const value = `%${descriptionFilter.value}%`;
            queryBuilder.andWhere(new typeorm_1.Brackets(qb => {
                qb.where('child_d.description ILIKE :description', { description: value });
                qb.orWhere('child_d.name ILIKE :name', { name: value });
            }));
        }
        const [items, total] = await queryBuilder.getManyAndCount();
        return { items, total };
    }
    async sunflowPowerPlants(params, context) {
        const { domain, user } = context.state;
        const descriptionFilter = params.filters.find(v => v.name === 'description');
        // 발전소 리스트
        const queryBuilder = (0, shell_1.getRepository)(shell_1.Domain)
            .createQueryBuilder('d')
            .select('d.id', 'id')
            .addSelect('d.name', 'name')
            .addSelect('d.description', 'description')
            .addSelect('d.subdomain', 'subdomain')
            .addSelect('d.attributes', 'attributes')
            .addSelect('d.createdAt', 'createdAt')
            .addSelect('d.updatedAt', 'updatedAt')
            .addSelect('c_pp.id', 'powerPlannerConnectionId')
            .addSelect('c_em.id', 'emissionMarketConnectionId')
            .addSelect("c_pp.params::json ->> 'username'", 'kepcoId')
            .addSelect("c_pp.params::json ->> 'password'", 'kepcoPassword')
            .leftJoin('connections', 'c_pp', `c_pp.domain_id = d.id AND c_pp.name = '${exports.POWER_PLANNER_CONNECTION_NAME}'`)
            .leftJoin('connections', 'c_em', `c_em.domain_id = d.id AND c_em.name = '${exports.EMISSION_MARKET_CONNECTION_NAME}'`)
            .where('d.extType IN (:...extTypes)', { extTypes: ['sunflow-power-plant', 'all-power-plant'] })
            .orderBy('d.name', 'ASC');
        if (descriptionFilter) {
            const value = `%${descriptionFilter.value}%`;
            queryBuilder.andWhere(new typeorm_1.Brackets(qb => {
                qb.where('d.description ILIKE :description', { description: value });
                qb.orWhere('d.name ILIKE :name', { name: value });
            }));
        }
        let items = await queryBuilder.getRawMany();
        const total = await queryBuilder.getCount();
        // connection 정보 가져오기
        for (const item of items) {
            item.attributes = JSON.parse(item.attributes);
            try {
                const powerPlannerConnection = await (0, shell_1.getRepository)(integration_base_1.Connection).findOne({
                    where: { id: item.powerPlannerConnectionId },
                    relations: ['domain']
                });
                // 발전소 정보 커넥션 확인
                if (powerPlannerConnection) {
                    // connection state 확인
                    const state = integration_base_1.ConnectionManager.getConnectionInstance(powerPlannerConnection)
                        ? integration_base_1.ConnectionStatus.CONNECTED
                        : integration_base_1.ConnectionStatus.DISCONNECTED;
                    item.powerPlannerConnectionState = state;
                }
                const emissionMarketConnection = await (0, shell_1.getRepository)(integration_base_1.Connection).findOne({
                    where: { id: item.emissionMarketConnectionId },
                    relations: ['domain']
                });
                // 배출권시장 정보 커넥션 확인
                if (emissionMarketConnection) {
                    const state = integration_base_1.ConnectionManager.getConnectionInstance(emissionMarketConnection)
                        ? integration_base_1.ConnectionStatus.CONNECTED
                        : integration_base_1.ConnectionStatus.DISCONNECTED;
                    item.emissionMarketConnectionState = state;
                }
            }
            catch (error) {
                item.powerPlannerConnectionState = null;
                item.emissionMarketConnectionState = null;
            }
        }
        return { items, total };
    }
};
exports.PowerPlantQuery = PowerPlantQuery;
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => shell_1.DomainList, { description: 'To fetch multiple PowerPlants' }),
    tslib_1.__param(0, (0, type_graphql_1.Args)()),
    tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [shell_1.ListParam, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "powerPlants", null);
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => power_plant_type_1.SunflowPowerPlantList, { description: 'To fetch multiple Sunflow PowerPlants' }),
    tslib_1.__param(0, (0, type_graphql_1.Args)()),
    tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [shell_1.ListParam, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "sunflowPowerPlants", null);
exports.PowerPlantQuery = PowerPlantQuery = tslib_1.__decorate([
    (0, type_graphql_1.Resolver)(shell_1.Domain)
], PowerPlantQuery);
//# sourceMappingURL=power-plant-query.js.map