"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const moment_timezone_1 = tslib_1.__importDefault(require("moment-timezone"));
const shell_1 = require("@things-factory/shell");
const auth_base_1 = require("@things-factory/auth-base");
const dataset_1 = require("@things-factory/dataset");
const inverter_1 = require("@esome-dev/inverter");
const DATE_INFO_FORMAT = 'YYYY-MM-DD HH:mm:ss';
process.on('bootstrap-module-global-public-route', (app, globalPublicRouter) => {
    /*
     * can add global public routes to application (auth not required, tenancy not required)
     *
     * ex) routes.get('/path', async(context, next) => {})
     * ex) routes.post('/path', async(context, next) => {})
     */
    globalPublicRouter.post('/monitoring/rtu/sensor/setup', async (context, next) => {
        const data = context.request.body;
        const { MFT_RTU_CD, DATE_INFO, RTU_IP } = data;
        if (!MFT_RTU_CD) {
            throw new Error(`MFT_RTU_CD(${MFT_RTU_CD}) properties are mandatory`);
        }
        await (0, shell_1.getDataSource)().transaction(async (tx) => {
            const appliance = await tx.getRepository(auth_base_1.Appliance).findOne({
                where: { name: MFT_RTU_CD },
                relations: ['domain']
            });
            if (!appliance) {
                throw new Error(`RTU having given MFT_RTU_CD(${MFT_RTU_CD}) not found`);
            }
            const domain = appliance.domain;
            const updatedAt = moment_timezone_1.default.tz(DATE_INFO, DATE_INFO_FORMAT, domain.timezone || 'Asia/Seoul').toDate();
            if (appliance) {
                await tx.getRepository(auth_base_1.Appliance).save(Object.assign(Object.assign({}, appliance), { netmask: RTU_IP, updatedAt }));
            }
        });
        context.status = 200;
    });
    globalPublicRouter.post('/monitoring/rtu/sensor/inverter', async (context, next) => {
        const data = context.request.body;
        const { MFT_RTU_CD, RTU_IVT_CD, DATE_INFO } = data;
        const sensorId = `${MFT_RTU_CD || ''}-${RTU_IVT_CD || ''}`;
        if (!MFT_RTU_CD || !RTU_IVT_CD) {
            throw new Error(`MFT_RTU_CD(${MFT_RTU_CD}) and INV-ID(${RTU_IVT_CD}) properties are mandatory`);
        }
        await (0, shell_1.getDataSource)().transaction(async (tx) => {
            const sensor = await tx.getRepository(dataset_1.DataSensor).findOne({
                where: { deviceId: sensorId },
                relations: ['domain', 'appliance', 'dataSet']
            });
            if (!sensor) {
                throw new Error(`Sensor having given sensorId(${sensorId}) not found`);
            }
            if (!sensor.active) {
                throw new Error(`State of the sensor given sensorId(${sensorId}) is not active`);
            }
            if (!sensor.appliance) {
                throw new Error(`Appliance of the sensor given sensorId(${sensorId}) is not set up`);
            }
            if (!sensor.dataSet) {
                throw new Error(`DataSet of the sensor given sensorId(${sensorId}) is not set up`);
            }
            const domain = sensor.domain;
            const dataSet = sensor.dataSet;
            const user = await tx.getRepository(auth_base_1.User).findOne({
                where: {
                    reference: sensor.appliance.id,
                    userType: 'appliance'
                }
            });
            context.state = Object.assign(Object.assign({}, context.state), { domain,
                tx });
            const collectedAt = moment_timezone_1.default.tz(DATE_INFO, DATE_INFO_FORMAT, domain.timezone || 'Asia/Seoul').toDate();
            await (0, dataset_1.createDataSample)({
                dataSet,
                data,
                rawData: data,
                source: sensorId,
                collectedAt
            }, context);
            const inverterStatus = await tx.getRepository(inverter_1.InverterStatus).findOne({
                where: {
                    domain: { id: domain.id },
                    rtuId: MFT_RTU_CD,
                    ivtId: RTU_IVT_CD
                }
            });
            if (inverterStatus && inverterStatus.collectedAt > collectedAt) {
                return;
            }
            const { ACC_P, AC_P, DC_P, DS, COM, RUN } = data;
            await tx.getRepository('InverterStatus').save(Object.assign(Object.assign({}, inverterStatus), { domain, rtuId: MFT_RTU_CD, ivtId: RTU_IVT_CD, acc: Number(ACC_P) || null, ac: Number(AC_P) || null, dc: Number(DC_P) || null, ds: Number(DS) || null, com: COM, run: RUN, collectedAt, updater: user }));
        });
        context.status = 200;
    });
    globalPublicRouter.post('/monitoring/rtu/sensor/weather', async (context, next) => {
        const data = context.request.body;
        const { MFT_RTU_CD, RTU_CDS_CD, DATE_INFO } = data;
        const sensorId = `${MFT_RTU_CD || ''}-${RTU_CDS_CD || ''}`;
        if (!MFT_RTU_CD || !RTU_CDS_CD) {
            throw new Error(`MFT_RTU_CD(${MFT_RTU_CD}) and RTU_CDS_CD(${RTU_CDS_CD}) properties are mandatory`);
        }
        await (0, shell_1.getDataSource)().transaction(async (tx) => {
            const sensor = await tx.getRepository(dataset_1.DataSensor).findOne({
                where: { deviceId: sensorId },
                relations: ['domain', 'appliance', 'dataSet']
            });
            if (!sensor) {
                throw new Error(`Sensor having given sensorId(${sensorId}) not found`);
            }
            if (!sensor.active) {
                throw new Error(`State of the sensor given sensorId(${sensorId}) is not active`);
            }
            if (!sensor.appliance) {
                throw new Error(`Appliance of the sensor given sensorId(${sensorId}) is not set up`);
            }
            if (!sensor.dataSet) {
                throw new Error(`DataSet of the sensor given sensorId(${sensorId}) is not set up`);
            }
            const domain = sensor.domain;
            const dataSet = sensor.dataSet;
            const user = await tx.getRepository(auth_base_1.User).findOne({
                where: {
                    reference: sensor.appliance.id,
                    userType: 'appliance'
                }
            });
            context.state = Object.assign(Object.assign({}, context.state), { domain,
                tx });
            const collectedAt = moment_timezone_1.default.tz(DATE_INFO, DATE_INFO_FORMAT, domain.timezone || 'Asia/Seoul').toDate();
            return await (0, dataset_1.createDataSample)({
                dataSet,
                data,
                rawData: data,
                source: sensorId,
                collectedAt
            }, context);
        });
        context.status = 200;
    });
});
process.on('bootstrap-module-global-private-route', (app, globalPrivateRouter) => {
    /*
     * can add global private routes to application (auth required, tenancy not required)
     */
});
process.on('bootstrap-module-domain-public-route', (app, domainPublicRouter) => {
    /*
     * can add domain public routes to application (auth not required, tenancy required)
     */
});
process.on('bootstrap-module-domain-private-route', (app, domainPrivateRouter) => {
    /*
     * can add domain private routes to application (auth required, tenancy required)
     */
});
//# sourceMappingURL=routes.js.map