
class PostgreSQL_Helper {
    constructor() {
        this.db_info = undefined;
        this.client = undefined;
        this.isConnected = false;
        this.pool = undefined;
        this.parent = undefined;
        this.conn_info = {
            isConn: false,
            isConnTry: true,
            recon_attemts: 0,
            completeFunc: undefined
        };
    }

    Set_Parent(parent) {
        this.parent = parent;
    }
    Set_Config(config) {
        this.db_info = config;
    }
    Get_Client() {
        return this.client;
    }
    Connect(success) {
        if (success) this.conn_info.completeFunc = success;

        var local_G = this;
        const { Pool } = require('pg');

        this.pool = new Pool({
            user: this.db_info.ID,
            host: this.db_info.HOST, // PostgreSQL 서버 호스트
            database: this.db_info.DATABASE,
            password: this.db_info.PW,
            port: Number(this.db_info.PORT),
            max: 20,
            idleTimeoutMillis: 30000,
            connectionTimeoutMillis: Number(this.db_info.CONNECT_TIMEOUT),
        });

        this.pool.connect().then((client) => {
            global.clog.info(`[PostgreSQL] Connected DB - \n ${local_G.db_info.HOST}:${local_G.db_info.PORT}`);
            local_G.conn_info.recon_attemts = 0;
            local_G.conn_info.isConn = true;
            local_G.conn_info.isConnTry = false;

            if (local_G.conn_info.completeFunc) {
                local_G.conn_info.completeFunc();
                local_G.conn_info.completeFunc = undefined;
            }
        }).catch((err) => {
            local_G.conn_info.recon_attemts++;

            //최대 재접속 횟수만큼 재접속 시도
            if (local_G.conn_info.recon_attemts <= local_G.db_info.RECONNECT_MAX_COUNT) {
                global.clog.info(`Reconnect To PostgreSQL DB - ${local_G.conn_info.recon_attemts}`);
                if (local_G.conn_info.isConnTry) local_G.Connect();
            }
            else {
                //최대 횟수 초과 시, 0 부터 다시 시작
                local_G.conn_info.recon_attemts = 0;
                local_G.db_info.HOST = "127.0.0.1"
                if (local_G.conn_info.isConnTry) local_G.Connect();
            }
        });

        this.pool.on('error', (err, client) => {
            console.log(err);
        })
    }
    //#region ACCOUNT
    async Query_ACCOUNTS() {
        try {
            let accounts_query = `SELECT * FROM public."VKR_ACCOUNT"`;
            return await this.pool.query(accounts_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_ACCOUNT_COUNT() {
        try {
            let count_query = `SELECT COUNT(*) FROM public."VKR_ACCOUNT"`;
            return await this.pool.query(count_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_ACCOUNT_GET(id) {
        try {
            let get_query = `SELECT * FROM public."VKR_ACCOUNT" WHERE id='${id}'`;
            return await this.pool.query(get_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_ACCOUNT_CHECK(id) {
        try {
            let check_query = `SELECT COUNT(*) FROM public."VKR_ACCOUNT" WHERE id='${id}'`;
            return await this.pool.query(check_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_ACCOUNT_ADD(data) {
        try {
            let columns = [
                'id', 'pwd', 'name', 'email', 'mobile',
                '"birthDate"', '"orgName"', '"orgDepart"',
                '"orgRole"', '"desc"', '"authorityType"', '"mdfDate"'
            ];
            let column_info = `${columns.join(', ')}`;
            let values =
                `'${data.id}', '${data.pwd}', '${data.name}','${data.email}','${data.mobile}',\
                '${data.birthDate}','${data.orgName}', '${data.orgDepart}',\
                '${data.orgRole}', '${data.desc}', '${data.authorityType}'`;
            
            let add_query = 
            `INSERT INTO public."VKR_ACCOUNT"(${column_info}) VALUES (${values}, CURRENT_TIMESTAMP)`;
            return await this.pool.query(add_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_ACCOUNT_DELETE(id) {
        try {
            let delete_query = `DELETE FROM public."VKR_ACCOUNT" WHERE id='${id}'`;
            return await this.pool.query(delete_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_ACCOUNT_UPDATE(data) {
        try {
            let columns = [ 
                `id='${data.id}'`, `pwd='${data.pwd}'`, `name='${data.name}'`, 
                `email='${data.email}'`, `mobile='${data.mobile}'`,
                `"birthDate"='${data.birthDate}'`, `"orgName"='${data.orgName}'`, `"orgDepart"='${data.orgDepart}'`, 
                `"orgRole"='${data.orgRole}'`, `"desc"='${data.desc}'`, `"authorityType"='${data.authorityType}'`, 
                '"mdfDate"=CURRENT_TIMESTAMP'
            ];
            let column_info = `${columns.join(', ')}`;
            let update_query = `
            UPDATE public."VKR_ACCOUNT" \
            SET ${column_info} \
            WHERE id = '${data.id}' RETURNING *`;
            return this.pool.query(update_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_ACCOUNT_SEARCH(data) {
        try {
            const offset = (Number(data.page) - 1) * Number(data.limit); // OFFSET 계산

            let _pre_query = this.pool.query(`
                SELECT COUNT(*) FROM public."VKR_ACCOUNT"
                ${data.where}
            `).then(
                function(query_res) {
                    return Number(query_res.rows[0].count);
                }
            ).catch(function (err) {
                throw err;
            });

            const _pre_count = await Promise.race([_pre_query]);

            const totalRows = _pre_count;
            const totalPages = Math.ceil(totalRows / Number(data.limit)); // 전체 페이지 수 계산

            const select_query = `
                SELECT "id", "name","authorityType","orgName","orgDepart","orgRole", "mobile"
                FROM public."VKR_ACCOUNT" 
                ${data.where}
                ORDER BY "${(data.sort == "CREATE_AT") ? "creDate" : "name"}" ${data.order} 
                LIMIT ${data.limit} OFFSET ${offset}
            `;
            const _pre_select = await Promise.race([this.pool.query(select_query)]);

            return {
                result_val : {
                    data: _pre_select.rows,
                    currentPage: Number(data.page),
                    totalPages: totalPages,
                    totalCount: totalRows
                },
                row_count:_pre_select.rowCount
            };
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_ACCOUNT_IDPW(id) {
        try {
            let idpwQuery = `SELECT * FROM public."VKR_ACCOUNT" WHERE id='${id}'`;
            return await this.pool.query(idpwQuery);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_TEST() {
        try {
            let accounts_query = `SELECT * FROM public.member`;
            return await this.pool.query(accounts_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    //#endregion

    //#region AUTH Query
    async Query_AUTH_IDCHECK(id) {
        try {
            let check_query = `SELECT COUNT(*) FROM public.member WHERE id='${id}'`;
            return await this.pool.query(check_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_AUTH_CREATE(data) {
        try {
            let columns = [
                'id', 'pw', 'name', 'pos', 'cls',
                '"creDate"', '"mdfDate"'
            ];
            let column_info = `${columns.join(', ')}`;
            let values = `'${data.id}', '${data.pw}', '${data.name}','${data.pos}','${data.cls}'`;
            
            let add_query = 
            `INSERT INTO public.member(${column_info}) VALUES (${values}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`;
            return await this.pool.query(add_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_AUTH_DELETE(id) {
        try {
            let delete_query = `DELETE FROM public.member WHERE id='${id}'`;
            return await this.pool.query(delete_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_AUTH_CHECK_LOGIN(id) {
        try {
            let delete_query = `SELECT id, pw, "isApprove" FROM public.member WHERE id='${id}'`;
            return await this.pool.query(delete_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_AUTH_ROLES() {
        try {
            let select_query = `SELECT name, "desc" FROM public.roles`;
            return await this.pool.query(select_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    //#endregion

    //#region EVENT & EVENT LOG
    async Query_EVENT(evtData) {
        try {
            let columns = [ 
                '"mgrId"', '"Door1"', '"Door2"', '"impact"', 
                '"tilt"', '"temperature"', '"humidity"',
                '"EML_1"', '"EML_2"', '"DeadboltL_1"', '"DeadboltL_2"',
                '"Fan_1"', '"Fan_2"', '"AC_1"', '"AC_2", "firmware"'
            ];
            let _mgrId = evtData.mgrId;
            let evtSen = evtData.sensor;
            let evtAct = evtData.actuator;
            let column_info = `${columns.join(', ')}`;
            let values = 
            `'${_mgrId}', '${evtSen.Door1}', '${evtSen.Door2}','${evtSen.impact}',\
            '${evtSen.tilt}','${evtSen.temperature}','${evtSen.humidity}',\
            '${evtAct.EML_1}','${evtAct.EML_2}','${evtAct.DeadboltL_1}','${evtAct.DeadboltL_2}',\
            '${evtAct.Fan_1}','${evtAct.Fan_2}','${evtAct.AC_1}','${evtAct.AC_2}', '${evtData.firmware}'`;
            let add_query = `INSERT INTO public."VKR_EVENT"(${column_info}) VALUES (${values})`;
            return await this.pool.query(add_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_EVENT_UPDATE(updateQuery) {
        try {
            return await this.pool.query(updateQuery);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_EVENT_TALLY() {
        try {
            var local_G = this;
            let all_query = `SELECT * FROM public."VKR_EVENT";`;
            let _pre_all_query = this.pool.query(all_query)
            .then(function(qRes) {
                let retVal = {
                    totalCount: qRes.rows.length,
                    open: 0,
                    close: 0,
                    hit: 0,
                    temp: 0,
                    humd: 0,
                    error: 0,
                    devices: []
                };
                if (qRes.rows.length > 0) {
                    for (let i = 0; i < qRes.rows.length; i++) {
                        let isError = false;
                        let rowItem = qRes.rows[i];
                        if (rowItem.Door1 == "Close") retVal.close += 1;
                        else if (rowItem.Door1 == "Open") retVal.open += 1;
                        if (rowItem.Door2 == "Close") retVal.close += 1;
                        else if (rowItem.Door2 == "Open") retVal.open += 1;

                        // if (rowItem.impact == "Hit") isError = true;

                        if (isError) retVal.error += 1;

                        rowItem.state = "NORMAL";
                        retVal.devices.push(rowItem);
                    }

                    let max_count = 500;
                    let bDebug = true
                    if (bDebug) {
                        let left_device = max_count - retVal.totalCount;
                        for (let i = 1; i <= left_device; i++) {
                            let dummy_device = {
                                mgrId: ``,
                                impact: 0,
                                tilt: 0,
                                temperature: 0,
                                humidity: 0,
                                EML_1: "Off",
                                EML_2: "Off",
                                DeadboltL_1: "Off",
                                DeadboltL_2: "Off",
                                Fan_1: "Off",
                                Fan_2: "Off",
                                AC_1: "Off",
                                AC_2: "Off",
                                Door1: "Close",
                                Door2: "Close",
                                state: "NORMAL"
                            }
                            retVal.devices.push(dummy_device);
                        }
                    }

                    return retVal;
                }
                return retVal;
            })
            .catch(function(err){
                throw err;
            })
            const _all_events = await Promise.race([_pre_all_query]);

            return {
                total_count:_all_events.totalCount,
                door: {
                    open: _all_events.open,
                    close: _all_events.close
                },
                devices: _all_events.devices
            }

        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_FACILITY_LOCNAME(mgrId) {
        try {
            let get_query = 
            `SELECT "mgrId", "locName" FROM public."VKR_FACILITY" WHERE "mgrId"='${mgrId}'`;
            return await this.pool.query(get_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    Query_EVENTLOGS(evtLogData) {
        let columns = [ 
            '"mgrId"', '"eventType"', '"eventDate"', '"eventVal"', 
            '"locName"', '"remark"'
        ];
        
        //#region eventType="ACCESS"인 경우, remark에 Door1 or Door2 남기기
        //eventType=logType, remark=eventType
        //eventType이 초기 설계와 다르게 실제로 들어오는 값이 다름름
        let _remark = "";
        try {
            _remark = evtLogData.eventType;
        }
        catch(error) {}
        //#endregion
        let column_info = `${columns.join(', ')}`;
        let values = 
        `'${evtLogData.mgrId}', '${evtLogData.logType}', '${evtLogData.eventDate}','${evtLogData.eventVal}',\
        '${evtLogData.locName}','${_remark}'`;
        let add_query = `INSERT INTO public."VKR_EVENTLOG"(${column_info}) VALUES (${values});`;
        return add_query;
    }
    async Query_TRANSACTION(query) {
        try {
            await this.pool.query('BEGIN');
            await this.pool.query(query);
            await this.pool.query('COMMIT');
        }
        catch(error) {
            await this.pool.query('ROLLBACK');
        }
    }
    async Query_EVENTLOG(evtLogData) {
        try {
            let columns = [ 
                '"mgrId"', '"eventType"', '"eventDate"', '"eventVal"', 
                '"locName"', '"grp1"', '"grp2"'
            ];
            let column_info = `${columns.join(', ')}`;
            let values = 
            `'${evtLogData.mgrId}', '${evtLogData.eventType}', '${evtLogData.eventDate}','${evtLogData.eventVal}',\
            '${evtLogData.locName}','${evtLogData.grp1}','${evtLogData.grp2}'`;
            let add_query = `INSERT INTO public."VKR_EVENTLOG"(${column_info}) VALUES (${values})`;
            return await this.pool.query(add_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    //#endregion
    //#region Setting GET & SAVE
    async Query_SETTING_GET(id) {
        try {
            let idpwQuery = `SELECT * FROM public."VKR_ADVANCED_SETTING" WHERE id='${id}'`;
            return await this.pool.query(idpwQuery);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_SETTING_SAVE(id, options) {
        try {
            let update_query = 
            `UPDATE public."VKR_ADVANCED_SETTING" \
            SET "tally_period_time_sec" = ${options.tally_period_time_sec} \
            WHERE id='${id}'`;
            return await this.pool.query(update_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    //#endregion
    //#region 그룹 API
    async Query_GROUPS() {
        try {
            let groupQuery = `SELECT 
                g1.id AS group1_id, 
                g1.name AS group1_name, 
                g1."creDate" AS group1_created, 
                g2.id AS group2_id, 
                g2.name AS group2_name, 
                g2."creDate" AS group2_created
            FROM public."VKR_CLASS_GROUP1" g1
            LEFT JOIN public."VKR_CLASS_GROUP2" g2 
                ON g2."refGroup1" = g1.id
            ORDER BY g1."creDate" DESC, g2."creDate" DESC NULLS LAST`;
            return await this.pool.query(groupQuery);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_GROUP_GET(id, type = "main") {
        try {
            let groupQuery = "";
            if (type == "main") {
                groupQuery = `SELECT 
                    g1.id AS group1_id, 
                    g1.name AS group1_name, 
                    g1."creDate" AS group1_created, 
                    g2.id AS group2_id, 
                    g2.name AS group2_name, 
                    g2."creDate" AS group2_created
                FROM public."VKR_CLASS_GROUP1" g1
                JOIN public."VKR_CLASS_GROUP2" g2 
                    ON g2."refGroup1" = g1.id
                WHERE g1.id = ${id}`
            }
            else {
                groupQuery = `SELECT 
                id, name, "creDate", "refGroup1" FROM public."VKR_CLASS_GROUP2" 
                WHERE id='${id}'`
            }
            return await this.pool.query(groupQuery);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_GROUP_ADD(data) {
        try {
            let addQuery = "";

            if (data.type == "main") {
                addQuery = `INSERT INTO public."VKR_CLASS_GROUP1"(name, "creDate") 
                VALUES ('${data.name}', CURRENT_TIMESTAMP)`;
            }
            else {
                addQuery = `INSERT INTO public."VKR_CLASS_GROUP2"(name, "refGroup1", "creDate") 
                SELECT '${data.name}', '${data.parentId}', CURRENT_TIMESTAMP
                WHERE EXISTS (
                    SELECT 1 FROM public."VKR_CLASS_GROUP1" WHERE id = '${data.parentId}'
                )`;
            }
            return await this.pool.query(addQuery);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_GROUP_DELETE(id, type) {
        try {
            let delQuery = "";
            if (type == "main") { 
                delQuery = `DELETE from public."VKR_CLASS_GROUP1" where id='${id}'`
            }
            else {
                delQuery = `DELETE from public."VKR_CLASS_GROUP2" where id='${id}'`
            }
            return await this.pool.query(delQuery);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_GROUP_UPDATE(data) {
        try {
            let updateQuery = "";
            if (data.type == "main") { 
                updateQuery = `UPDATE public."VKR_CLASS_GROUP1"
                SET name='${data.name}'
                WHERE id='${data.id}'`
            }
            else {
                updateQuery = `UPDATE public."VKR_CLASS_GROUP2"
                SET name='${data.name}'
                WHERE id='${data.id}'`
            }

            return await this.pool.query(updateQuery);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    //#endregion
    //#region 설치구분 API
    async Query_INTENDED_SEARCH(data) {
        try {
            const offset = (Number(data.page) - 1) * Number(data.limit); // OFFSET 계산

            let _pre_query = this.pool.query(`
                SELECT COUNT(*) FROM public."VKR_INTENDED_USE"
                ${data.where}
            `).then(
                function(query_res) {
                    return Number(query_res.rows[0].count);
                }
            ).catch(function (err) {
                throw err;
            });

            const _pre_count = await Promise.race([_pre_query]);

            const totalRows = _pre_count;
            const totalPages = Math.ceil(totalRows / Number(data.limit)); // 전체 페이지 수 계산

            let select_query = "";
            if (data.type == "ALL") {
                //all 이미지 포함
                select_query = `
                    SELECT id, name, "imgData", "creDate", "mdfDate", "imgFileName" 
                    FROM public."VKR_INTENDED_USE" 
                    ${data.where}
                    ORDER BY "${(data.sort == "CREATE_AT") ? "creDate" : "name"}" ${data.order} 
                    LIMIT ${data.limit} OFFSET ${offset}
                `;
            }
            else {
                //light 이미지 미포함
                select_query = `
                    SELECT id, name 
                    FROM public."VKR_INTENDED_USE" 
                    ${data.where}
                    ORDER BY "${(data.sort == "CREATE_AT") ? "creDate" : "name"}" ${data.order} 
                    LIMIT ${data.limit} OFFSET ${offset}
                `;
            }

            const _pre_select = await Promise.race([this.pool.query(select_query)]);

            return {
                result_val : {
                    data: _pre_select.rows,
                    currentPage: Number(data.page),
                    totalPages: totalPages,
                    totalCount: totalRows
                },
                row_count:_pre_select.rowCount
            };
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_INTENDED_CHECK(id) {
        try {
            let check_query = `SELECT COUNT(*) FROM public."VKR_INTENDED_USE" WHERE id='${id}'`;
            return await this.pool.query(check_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_INTENDED_GET(id) {
        try {
            let get_query = `SELECT * FROM public."VKR_INTENDED_USE" WHERE id='${id}'`;
            return await this.pool.query(get_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_INTENDED_ADD(data) {
        try {
            let columns = [ 
                '"name"', '"imgData"', '"creDate"', '"mdfDate"', '"imgFileName"'
            ];
            let column_info = `${columns.join(', ')}`;
            let values = `'${data.name}', '${data.imgData}', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '${data.imgFileName}'`;
            let add_query = 
            `INSERT INTO public."VKR_INTENDED_USE"(${column_info}) VALUES (${values})`;
            return await this.pool.query(add_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_INTENDED_DELETE(id) {
        try {
            let delete_query = `DELETE FROM public."VKR_INTENDED_USE" WHERE id='${id}'`;
            return await this.pool.query(delete_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_INTENDED_UPDATE(data) {
        try {
            let update_query = "";

            if (data.isImgDelete == "true") {
                //이미지 삭제한 경우,
                update_query = `UPDATE public."VKR_INTENDED_USE"
                SET name='${data.name}', "imgData"='', "mdfDate"=CURRENT_TIMESTAMP, 
                "imgFileName"=''
                WHERE id='${data.id}'`
            }
            else {
                //삭제 안한 경우, 이미지 내용 없으면 업데이트 안함
                if (data.imgData) {
                    update_query = `UPDATE public."VKR_INTENDED_USE"
                    SET name='${data.name}', "imgData"='${data.imgData}', "mdfDate"=CURRENT_TIMESTAMP, 
                    "imgFileName"='${data.imgFileName}'
                    WHERE id='${data.id}'`
                }
                else {
                    update_query = `UPDATE public."VKR_INTENDED_USE"
                    SET name='${data.name}', "mdfDate"=CURRENT_TIMESTAMP WHERE id='${data.id}'`
                }
                
            }

            return await this.pool.query(update_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    //#endregion
    //#region OTA (펌웨어)
    async Query_OTA_SEARCH(data) {
        try {
            const offset = (Number(data.page) - 1) * Number(data.limit); // OFFSET 계산

            let _pre_query = this.pool.query(`
                SELECT COUNT(*) FROM public."VKR_FIRMWARE"
                ${data.where}
            `).then(
                function(query_res) {
                    return Number(query_res.rows[0].count);
                }
            ).catch(function (err) {
                throw err;
            });

            const _pre_count = await Promise.race([_pre_query]);

            const totalRows = _pre_count;
            const totalPages = Math.ceil(totalRows / Number(data.limit)); // 전체 페이지 수 계산

            let select_query = `
                SELECT * FROM public."VKR_FIRMWARE" 
                ${data.where}
                ORDER BY "${(data.sort == "CREATE_AT") ? "creDate" : "verValue"}" ${data.order} 
                LIMIT ${data.limit} OFFSET ${offset}
            `;

            const _pre_select = await Promise.race([this.pool.query(select_query)]);

            return {
                result_val : {
                    data: _pre_select.rows,
                    currentPage: Number(data.page),
                    totalPages: totalPages,
                    totalCount: totalRows
                },
                row_count:_pre_select.rowCount
            };
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_OTA_GET(ver) {
        try {
            let get_query = `SELECT * FROM public."VKR_FIRMWARE" WHERE version='${ver}'`;
            return await this.pool.query(get_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_OTA_DELETE(ver) {
        try {
            let delete_query = `DELETE FROM public."VKR_FIRMWARE" WHERE version='${ver}'`;
            return await this.pool.query(delete_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_OTA_LATEST() {
        try {
            let get_query = `SELECT * FROM public."VKR_FIRMWARE" order by "verValue" DESC`;
            return await this.pool.query(get_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    async Query_OTA_ADD(data) {
        try {
            let columns = [
                'version', 'filename', '"downUrl"', 'filesize', '"verValue"', '"creDate"'
            ];
            let column_info = `${columns.join(', ')}`;
            let values =
            `'${data.version}', '${data.filename}', '${data.downUrl}', '${data.filesize}', '${data.verValue}'`;
            let add_query = 
            `INSERT INTO public."VKR_FIRMWARE"(${column_info}) VALUES (${values}, CURRENT_TIMESTAMP)`;
            return await this.pool.query(add_query);
        }
        catch(err) {
            return Promise.reject(err);
        }
    }
    //#endregion
}

module.exports = PostgreSQL_Helper;
