Source: models/core/handlerAlarm.js

/**
 * 
 *  Handles incoming alarm information and persists them 
 *  at the coredatabase.
 * 
 *  (c) Jens Dinstühler 2020
 * 
 *  Version 1.0.0
 * 
 * 
 */

const EventEmitter = require('events');
const Alarm = require('../alarm');
const FeedbackStore = require('./feedbackstore');
const Feedbackstore = require('./feedbackstore');

class CoreAlarmHandler extends EventEmitter {
    constructor() {
        super();
    }

    /**
     * Checks if for the given operationnumber an operation entry exists in database
     * @param {string} operationnumber 
     * @param {function} callback 
     */
    checkOperationNumberExists(operationnumber, callback) {
        global.plgManager.logger.debug('CORE | HANDLERALARM | checking for existing operationnumber: ' + operationnumber);
                   
        if (typeof operationnumber === 'string') {
            var checkSql = "SELECT * FROM operationsStore WHERE operationnumber = '" + operationnumber + "'";
            global.coreDb.all(checkSql, [], (err, rows) => {
                if (err) {
                    global.plgManager.logger.error('CORE | HANDLERALARM | Error checking for existing operationnumber: ' + err.message);
                    return 0;
                } else {
                    if (rows.length > 0) {
                        return callback(rows[0].id);
                    } else {
                        return callback(0);
                    }
                }
            });
        } else {
            // no valid data for operationnumber
            return callback(0);
        }
    }

    /**
     * Saves new alarm Information into core database
     * @param {alarmInfo} alarmInfo 
     */
    persistNewAlarmInformation(alarmInfo) {
        if ((typeof alarmInfo != 'undefined')) {
            // Check if operation exists (key is operationnumber)
            this.checkOperationNumberExists(alarmInfo.operationnumber.value, (opId) => {
                var zveisCalc = '';
                if (typeof alarmInfo.zveisCalc.value !== 'undefined') {
                    try {
                        if (alarmInfo.zveisCalc.value.length > 0) {
                            zveisCalc = JSON.stringify(alarmInfo.zveisCalc.value);
                        }
                    } catch (err) {
                        // Error rendering JSON String
                    }
                }
                
                var gearCalc = '';
                if (typeof alarmInfo.gearCalc.value !== 'undefined') {
                    try {
                        if (alarmInfo.gearCalc.value.length > 0) {
                            gearCalc = JSON.stringify(alarmInfo.gearCalc.value);
                        }
                    } catch (err) {
                        // Error rendering JSON String
                    }
                }
                
                if (alarmInfo.operationState.value === null) {
                    alarmInfo.operationState = 0;
                }

                global.plgManager.logger.info('CORE | HANDLERALARM | operationState reported as: ' + alarmInfo.operationState.value);

                global.coreDb.run(
                    `INSERT INTO operationsStore (` +
                    `alarmdate, ` +
                    `alarmtime, ` +
                    `alarmtimeCalc, ` +
                    `gear, ` +
                    `gearlistCalc, ` +
                    `operationnumber, ` +
                    `location, ` +
                    `message, ` +
                    `community, ` +
                    `rawdata, ` +
                    `object, ` +
                    `district, ` +
                    `keywordId, ` +
                    `keywordCategory, ` +
                    `keywordRaw, ` +
                    `keywordName, ` +
                    `zveis, ` +
                    `zveisListCalc, ` +
                    `subject, ` +
                    `street, ` +
                    `gkx, ` +
                    `gky, ` +
                    `lat, ` +
                    `lon, ` +
                    `operationState, ` +
                    `operationSourceConnector, ` +
                    `subOperationFor, ` +
                    `uuid, ` + 
                    `floor, ` +
                    `ils` +
                    `) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                    [
                        alarmInfo.alarmdate.value,
                        alarmInfo.alarmtime.value,
                        alarmInfo.alarmtimeCalc.value,
                        alarmInfo.gear.value,
                        gearCalc,
                        alarmInfo.operationnumber.value,
                        alarmInfo.location.value,
                        alarmInfo.message.value,
                        alarmInfo.community.value,
                        alarmInfo.rawdata.value,
                        alarmInfo.object.value,
                        alarmInfo.district.value,
                        alarmInfo.keywordId.value,
                        alarmInfo.keywordCategory.value,
                        alarmInfo.keywordRaw.value,
                        alarmInfo.keywordName.value,
                        alarmInfo.zveis.value,
                        zveisCalc,
                        alarmInfo.subject.value,
                        alarmInfo.street.value,
                        alarmInfo.gkx.value,
                        alarmInfo.gky.value,
                        alarmInfo.lat.value,
                        alarmInfo.lon.value,
                        0,
                        alarmInfo.operationSourceConnector.value,
                        opId,
                        alarmInfo.uuid.value,
                        alarmInfo.floor.value,
                        alarmInfo.ils.value
                    ],
                    function (err) {
                        if (err) {
                            global.plgManager.logger.error('CORE | HANDLERALARM | Error inserting new alarm to coredatabase: ' + err.message);
                            console.log('CORE | HANDLERALARM | Error inserting new alarm to coredatabase: ' + err.message);
                        } else {
                            var insertId = this.lastID;
                            global.plgManager.logger.debug(`CORE | HANDLERALARM | New Alarm Info has been inserted to coredatabase (id: ${insertId})`);
                            console.log(`CORE | HANDLERALARM | New Alarm Info has been inserted to coredatabase (id: ${insertId})`);
                            var alarm = new Alarm();
                            alarm.getAllAlarmingUUIDsForNamespace('alarmiatormobile', (uuidArray) => {
                                if (Array.isArray(uuidArray)) {
                                    console.log('CORE | HANDLERALARM | Adding now feedbackState entries for ' + uuidArray.length + ' basedata members');
                                    var feedbackstore = new FeedbackStore(global.app.logger);
                                    feedbackstore.generateFeedbackObjectsForOperation(insertId, uuidArray, (success) => {
                                        if (success) {
                                            console.log('CORE | HANDLERALARM | Successfully added feedbackstore objects for basedata members');
                                        } else {
                                            console.log('CORE | HANDLERALARM | Could not add feedbackstore objects for basedata members');
                                        }
                                    })
                                } else {
                                    console.log('CORE | HANDLERALARM | no UUIDS for feedbackStates found.');
                                }
                            })
                        }
                    });

            })

        } else {
            global.plgManager.logger.error('CORE | HANDLERALARM | Error persisting alarm');
        }
    }
}

module.exports = CoreAlarmHandler;