Source: models/alertdevices.js

const EventEmitter = require('events');
const basedata = require('./basedata');
const { isNull } = require('util');

/**
 * Class represents alertdevices in ALARMiator Core
 * @class
 * @author Jens Dinstühler
 */
class Alertdevices extends EventEmitter {

    /**
     * @constructor
     * @param {object} logger logger instance to be used by this class instance.
     */
    constructor(logger) {
        super();
        this.logger = logger;
    }

    /**
     * Returns all Alert Devices from core database
     * @param {function} callback rows or null
     */
    getAllAlertdevices(callback) {
        let query = "SELECT " +
                        "alertdevices.*, " +
                        "basedata.firstname AS bDataFirstname, " +
                        "basedata.lastname AS bDataLastname, " +
                        "organizations.name AS orgName, " +
                        "organizations.id AS orgId " +
                    "FROM alertdevices " +
                    "INNER JOIN basedata ON basedata.id = alertdevices.basedataId " +
                    "INNER JOIN organizations ON organizations.id = basedata.organizationid";

        global.coreDb.all(query, [], (err, rows) => {
            if (err) {
                console.log(err);
                this.logger.error('MODELS-ALERDEVICES | Error getAllAlertdevices: ' + err.message);
                return callback([]);
            } else {
                return callback(rows);
            }
        });
    }

    /**
     * Returns Alert Device from core database with given uuid
     * @param {string} uuid uuid of device to return from core database
     * @param {function} callback rows or null
     */
    getAlertdeciceForUUID(uuid, callback) {
        let query = "SELECT * FROM alertdevices WHERE uuid = ?";

        global.coreDb.all(query, [
            uuid
        ], (err, rows) => {
            if (err) {
                console.log(err);
                this.logger.error('MODELS-ALERDEVICES | Error getAllAlertdevices: ' + err.message);
                return callback([]);
            } else {
                return callback(rows);
            }
        });
    }



    /**
     * Creates a new device in coredatabase table
     * @param {integer} basedataId id of basedata this device belongs to
     * @param {integer} assetsId asset id of asset, this device belongs to
     * @param {string} name name of device
     * @param {string} model model of device
     * @param {string} platform platform of the device
     * @param {string} osVersion OS Version reported by device
     * @param {string} uuid uuid of device
     * @param {integer} state state (1 active, 0 inactive)
     * @param {function} callback success (true or false)
     */
    createDevice(basedataId, assetsId, name, model, platform, osVersion, uuid, state, callback) {

        // prepare data
        if (basedataId !== isNull) {
            if (basedataId.length < 1) {
                basedataId = null;
            }
        }
        if (assetsId !== null) {
            if (assetsId.length < 1) {
                assetsId = null;
            }
        }

        // Set Timestamp for registration date
        var registrationDate = new Date();
        let query = "INSERT INTO alertdevices (basedataId, assetsId, name, model, platform, osVersion, uuid, state, registeredAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        global.coreDb.run(query, [
            basedataId,
            assetsId,
            name,
            model,
            platform,
            osVersion,
            uuid,
            state,
            registrationDate
        ], function (err) {
            if (err) {
                console.log('MODELS-ALERTDEVICES | Error storing new device to database: ' + err.message);
                callback(false);
            } else {
                callback(true);
            }
        });
    }

    /**
     * 
     * @param {integer} deviceId id of device in core database table alertdevices
     * @param {function} callback success (true or false)
     */
    removeDevice(deviceId, callback) {
        let query = "DELETE FROM alertdevices WHERE id = ?";

        global.coreDb.run(query, [
            deviceId
        ], function (err) {
            if (err) {
                callback(false);
            } else {
                callback(true);
            }
        });
    }

    /**
     * Deletes a device from core database given by its uuis
     * @param {string} uuid uuid of device to delete
     * @param {function} callback success (true/false)
     */
    removeDeviceByUUID(uuid, callback) {
        let query = "DELETE FROM alertdevices WHERE uuid = ?";

        global.coreDb.run(query, [
            uuid
        ], function (err) {
            if (err) {
                callback(false);
            } else {
                callback(true);
            }
        });
    }

    /**
     * Updates device information in core database. basedataId and assetId can not be updated as a device can not be moved from one person / asset to another.
     * @param {integer} deviceId id of device in coredatabase table alertdevices to be updated now
     * @param {string} name name of device
     * @param {string} model model of device
     * @param {string} platform platform of device
     * @param {string} osVersion osVersion of device
     * @param {string} uuid uuid of device
     * @param {function} callback success (true or false)
     */
    updateDevice(deviceId, name, model, platform, osVersion, uuid, callback) {
        let query = "UPDATE alertdevices SET " +
            "name = ?, " +
            "model = ?, " +
            "platform = ?, " +
            "osVersion = ?, " +
            "uuid = ?, " +
            "WHERE id = ?";

            global.coreDb.run(query, [
                name,
                model, 
                platform,
                osVersion,
                uuid,
                deviceId
            ], function (err) {
                if (err) {
                    callback(false);
                } else {
                    this.updateLastSeenById(deviceId, (successUpdate) => {
                        if (successUpdate) {
                            callback(true);
                        } else {
                            callback(false);
                        }
                    })
                    
                }
            });
    }

    /**
     * Sets the state of an device to active
     * @param {integer} deviceId id of device in coredatabase to set state for
     * @param {function} callback success (true or false)
     */
    setActive(deviceId, callback) {
        let query = "UPDATE alertdevices SET state = ? WHERE id = ?";
        global.coreDb.run(query, [
            1,
            deviceId
        ], function (err) {
            if (err) {
                callback(false);
            } else {
                callback(true);
            }
        });
    }

    /**
     * Sets the state of an device to inactive
     * @param {integer} deviceId id of device in coredatabase to set state for
     * @param {function} callback success (true or false)
     */
    setInactive(deviceId, callback) {
        let query = "UPDATE alertdevices SET state = ? WHERE id = ?";
        global.coreDb.run(query, [
            0,
            deviceId
        ], function (err) {
            if (err) {
                callback(false);
            } else {
                callback(true);
            }
        });
    }

    /**
     * Checks, if a device exists in database
     * @param {string} uuid 
     * @param {function} callback null or row of existing device
     */
    doesDeviceExist(uuid, callback) {
        let query = "SELECT * FROM alertdevices WHERE uuid = ?";

        global.coreDb.all(query, [
            uuid
        ], (err, rows) => {
            if (err) {
                return null;
            } else {
                return callback(rows);
            }
        });
    }

    /**
     * Updates the last seen timestamp for device with uuid
     * @param {string} uuid 
     * @param {function} callback success (true / false)
     */
    updateLastSeenByUUID(uuid, callback) {
        var lastSeen = new Date();
        let query = "UPDATE alertdevices SET lastseen = ? WHERE uuid = ?";
        global.coreDb.run(query, [
            lastSeen,
            uuid
        ], function (err) {
            if (err) {
                callback(false);
            } else {
                callback(true);
            }
        });
    }

    /**
     * Updates the last seen timestamp for device with id
     * @param {string} uuid 
     * @param {function} callback success (true / false)
     */
    updateLastSeenById(id, callback) {
        var lastSeen = new Date();
        let query = "UPDATE alertdevices SET lastseen = ? WHERE id = ?";
        global.coreDb.run(query, [
            lastSeen,
            id
        ], function (err) {
            if (err) {
                callback(false);
            } else {
                callback(true);
            }
        });
    }

}

module.exports = Alertdevices;