/**
 * ==================================================
 * Device Service
 * ==================================================
 */

const db = require("../config/db");

class DeviceService {

    // ==========================================
    // Dashboard Statistics
    // ==========================================

    async getDashboard() {

        const [[total]] = await db.query(`
            SELECT COUNT(*) total
            FROM devices
        `);

        const [[online]] = await db.query(`
            SELECT COUNT(*) online
            FROM devices
            WHERE status='Online'
        `);

        const [[offline]] = await db.query(`
            SELECT COUNT(*) offline
            FROM devices
            WHERE status='Offline'
        `);

        const [[response]] = await db.query(`
            SELECT
            ROUND(AVG(response_time),0) responseTime
            FROM devices
        `);

        return {

            total: Number(total.total),

            online: Number(online.online),

            offline: Number(offline.offline),

            responseTime:
                Number(response.responseTime || 0)

        };

    }

    // ==========================================
    // Device List
    // ==========================================

    async getDevices() {

        const [rows] = await db.query(`

            SELECT

                id,

                device_name,

                device_code,

                device_type,

                ip_address,

                firmware_version,

                status,

                response_time,

                last_heartbeat

            FROM devices

            ORDER BY id ASC

        `);

        return rows.map(device => ({

            id: device.id,

            name: device.device_name,

            device_id: device.device_code,

            type: device.device_type,

            ip_address: device.ip_address,

            firmware: device.firmware_version,

            status: device.status,

            responseTime: device.response_time,

            last_heartbeat:
                device.last_heartbeat

        }));

    }

    // ==========================================
    // Device Details
    // ==========================================

    async getDevice(id) {

        const [[device]] = await db.query(`

            SELECT *

            FROM devices

            WHERE id=?

        `,[id]);

        return device;

    }

}

module.exports = new DeviceService();