"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIBase = void 0;
const RawQuery_1 = require("../lib/model/RawQuery");
const net_1 = require("net");
const setting_config_1 = require("../config/setting.config");
const markError_1 = require("./markError");
const RawNonQuery_1 = require("../lib/model/RawNonQuery");
var request = require('request');
const vs_server = new setting_config_1.VoiceServer();
const prefix = vs_server.Prefix;
class APIBase {
    constructor() {
    }
    getLRN(lrn_detail) {
        if (lrn_detail.hasOwnProperty('errors')) {
            if (lrn_detail.errors[0] == "LRN Not Found.") {
                return true;
            }
            else
                return false;
        }
        else
            return false;
    }
    getRate(req, res, tariff, type, category, callback) {
        let catagory = category == 'TF' ? "toll_free_number" : "local_number";
        let obj1 = new RawQuery_1.ModelRawQuery(req, res);
        obj1.qrysql = "SELECT `rate` FROM `voice_rates` WHERE `idtariff`='" + tariff + "'  AND `category`='" + catagory + "' AND `type`='" + type + "' LIMIT 1";
        obj1.prepare();
        obj1.execute((err, rates) => {
            callback(err, rates);
        });
    }
    getRateCenter(req, res, npa, nxx, callback) {
        let obj = new RawQuery_1.ModelRawQuery(req, res);
        obj.qrysql = "SELECT   `rc_abbre`, `loc_state` FROM `did_location_info` WHERE `npa`='" + npa + "'  AND `nxx`='" + nxx + "'";
        obj.prepare();
        obj.execute((err, ratecenter_state) => {
            if (ratecenter_state.length > 0) {
                callback('', ratecenter_state);
            }
            else {
                callback(err, '');
            }
        });
    }
    verifyBrand(req, res, npa, callback) {
        let obj = new RawQuery_1.ModelRawQuery(req, res);
        obj.qrysql = "SELECT   `brand_name` FROM `brand` WHERE `idaccount`=''";
        obj.prepare();
        obj.execute((err, ratecenter_state) => {
            if (ratecenter_state.length > 0) {
                callback('', ratecenter_state);
            }
            else {
                callback(err, '');
            }
        });
    }
    verifyCampagin(req, res, npa, nxx, callback) {
        let obj = new RawQuery_1.ModelRawQuery(req, res);
        obj.qrysql = "SELECT   `idbrand` FROM `campaign` WHERE `npa`='" + npa + "'";
        obj.prepare();
        obj.execute((err, ratecenter_state) => {
            if (ratecenter_state.length > 0) {
                callback('', ratecenter_state);
            }
            else {
                callback(err, '');
            }
        });
    }
    getLrnDetails(req, res, did, callback) {
        did = "" + did + "";
        let len = did.length - 10;
        let number = did.slice(len, did.length);
        let npa = number.slice(0, 3);
        let nxx = number.slice(3, 6);
        let obj1 = new RawQuery_1.ModelRawQuery(req, res);
        obj1.qrysql = "SELECT *  FROM `lerg_info` WHERE `npa`='" + npa + "' AND `nxx`='" + nxx + "'";
        obj1.prepare();
        obj1.execute((err, lrn_details) => {
            if (lrn_details.length > 0) {
                callback('', lrn_details);
            }
            else {
                callback(err, '');
            }
        });
    }
    generateInsertQuery(payload, funDetail) {
        if (!payload || Object.keys(payload).length === 0) {
            console.log({ status: 504, message: "Payload is empty for " + funDetail.logName + ' from function ' + funDetail.functionName });
            return '';
        }
        else {
            const setQuery = Object.entries(payload).map(([key, value]) => {
                switch (typeof value) {
                    case "string":
                        return `\`${key}\` = '${(0, markError_1.parseBody)(value)}'`;
                    case "number":
                        return `\`${key}\` = '${(0, markError_1.setToZero)(value)}'`;
                    case "boolean":
                        return `\`${key}\` = '${value ? 'true' : 'false'}'`;
                    case "object":
                        return value === null ? `\`${key}\` = ''` : `\`${key}\` = '${JSON.stringify(value)}'`;
                    case "undefined":
                    default:
                        return `\`${key}\` = ''`;
                }
            }).join(", ");
            return `INSERT INTO \`${funDetail.tableName}\` SET ${setQuery};`;
        }
    }
    insertLog(req, res, payload, callback) {
        console.log("The " + payload.funDetail.logName + " Log is generating for ", payload.funDetail.functionName);
        if (payload.data && Object.keys(payload.data).length > 0) {
            if (!payload.data || Object.keys(payload.data).length === 0) {
                console.log({ status: 504, message: payload.funDetail.logName + " Log Data Not Available" });
                return;
            }
            try {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                let qry = this.generateInsertQuery(payload.data, payload.funDetail);
                if (qry) {
                    obj.nonqrysql = qry;
                    console.log("Generated Query:", obj.nonqrysql);
                    obj.prepare();
                    obj.execute((error, result) => {
                        if (error == 1) {
                            console.log({ status: 200, message: payload.funDetail.logName + " Log Inserted for function " + payload.funDetail.functionName });
                            callback(1, error);
                        }
                        else {
                            callback(0, result);
                            console.log({ status: 502, message: payload.funDetail.logName + " Log Not Inserted for function " + payload.funDetail.functionName });
                        }
                    });
                }
                else {
                    console.log({ status: 506, message: payload.funDetail.logName + " Log Query Not created for function " + payload.funDetail.functionName });
                }
            }
            catch (err) {
                console.error(payload.funDetail.functionName + " =:> Error generating query for :", payload.funDetail.logName, "Log =>", err.message);
            }
        }
    }
    DialCall(req, res, next, sessdata, lerg_data, vrate, callback) {
        let socketData = '{caller_id_number=' + req.body.CALLER.trim() + ',dialed_number=' + req.body.CALLEE.trim() + ',effective_caller_id_name=' + req.body.CALLER.trim() + ',iduser=' + sessdata.iduser + ',idapi=' + sessdata.idapi + ',accountcode=' + sessdata.idaccount + ',leg_to=' + vrate.getCallRate(req.body.CALLER) + ',amd_rate=' + vrate.AMDRate(req.body.AMD) + ',rec_rate=' + vrate.RecordRate(req.body.Recording) + ',ctype=4,ocn=' + lerg_data[0].ocn + ',category=' + lerg_data[0].category + ',mobility=' + lerg_data[0].co_name_spec_c + ',effective_caller_id_number=' + req.body.CALLER.trim() + ',origination_caller_id_name=' + req.body.CALLER.trim() + ',origination_caller_id_number=' + req.body.CALLER.trim() + '}sofia/gateway/iplink/' + prefix + req.body.CALLER.trim() + ' &bridge({caller_id_number=' + req.body.FROM.trim() + ',dialed_number=' + req.body.CALLEE.trim() + ',effective_caller_id_name=' + req.body.FROM.trim() + ',effective_caller_id_number=' + req.body.FROM.trim() + ',iduser=' + sessdata.iduser + ',idapi=' + sessdata.idapi + ',accountcode=' + sessdata.iduser + ',leg_from=' + vrate.getCallRate(req.body.CALLER) + ',amd_rate=' + vrate.AMDRate(req.body.AMD) + ',ctype=4,rec_rate=' + vrate.RecordRate(req.body.Recording) + ',lata=' + lerg_data[0].lata + ',origination_caller_id_name=' + req.body.FROM.trim() + ',origination_caller_id_number=' + req.body.FROM.trim() + '}sofia/gateway/iplink/' + prefix + req.body.CALLEE.trim() + ')';
        let client = new net_1.Socket();
        client.connect(parseInt(vs_server.PORT), vs_server.HOST, function () {
            client.write('auth ' + vs_server.PASS + '\n\n');
            ;
            client.write('api originate ' + socketData + '\n\n');
            client.on("data", (respon) => {
                let tmp = respon.toString().split("\n");
                tmp.forEach((elem) => {
                    if (elem != undefined) {
                        if (elem.length > 0) {
                            let t1 = elem.split("OK");
                            if (t1.length == 2) {
                                if (t1[0] == "+") {
                                    res.send({ status: 201, message: "Call connected successfully", uuid: t1[1].trim() });
                                }
                            }
                            let t2 = elem.split("ERR");
                            if (t2.length == 2) {
                                res.send({ status: 404, message: t2[1].trim() });
                                client.end();
                            }
                        }
                    }
                });
            });
            client.on("error", (e) => {
            });
            client.on("end", (err) => {
            });
        });
    }
    makeCall(req, res, next, sessdata, lerg_data, vrate, callback) {
        let socketData = '{caller_id_number=' + req.body.FROM.trim() + ',dialed_number=' + req.body.TO.trim() + ',effective_caller_id_name=' + req.body.FROM.trim() + ',effective_caller_id_number=' + req.body.FROM.trim() + ',iduser=' + sessdata.iduser + ',idapi=' + sessdata.idapi + ',accountcode=' + sessdata.idaccount + ',leg_from=' + vrate.getCallRate(req.body.Extension) + ',amd_rate=' + vrate.AMDRate(req.body.AMD) + ',rec_rate=' + vrate.RecordRate(req.body.Recording) + ',origination_caller_id_name=' + req.body.FROM.trim() + ',origination_caller_id_number=' + req.body.FROM.trim() + '}user/' + req.body.Extension.trim() + ' &bridge({caller_id_number=' + req.body.FROM.trim() + ',dialed_number=' + req.body.TO.trim() + ',effective_caller_id_name=' + req.body.FROM.trim() + ',iduser=' + sessdata.iduser + ',idapi=' + sessdata.idapi + ',accountcode=' + sessdata.iduser + ',leg_to=' + vrate.getCallRate(req.body.TO) + ',amd_rate=' + vrate.AMDRate(req.body.AMD) + ',rec_rate=' + vrate.RecordRate(req.body.Recording) + ',ocn=' + lerg_data[0].ocn + ',category=' + lerg_data[0].category + ',mobility=' + lerg_data[0].co_name_spec_c + ',effective_caller_id_number=' + req.body.FROM.trim() + ',origination_caller_id_name=' + req.body.FROM.trim() + ',origination_caller_id_number=' + req.body.FROM.trim() + '}sofia/gateway/iplink/' + prefix + req.body.TO.trim() + ')';
        let client = new net_1.Socket();
        client.connect(parseInt(vs_server.PORT), vs_server.HOST, function () {
            console.log('CONNECTED TO: ' + vs_server.HOST + ':' + vs_server.PORT);
            client.write('auth ' + vs_server.PASS + '\n\n');
            console.log("Password : " + vs_server.PASS);
            console.log(socketData);
            client.write('api originate ' + socketData + '\n\n');
            client.on("data", (respon) => {
                let tmp = respon.toString().split("\n");
                tmp.forEach((elem) => {
                    if (elem != undefined) {
                        if (elem.length > 0) {
                            console.log(elem);
                            let t1 = elem.split("OK");
                            if (t1.length == 2) {
                                console.log(t1);
                                if (t1[0] == "+") {
                                    res.status(200).send({ message: "Call Connected Successfully", uuid: t1[1].trim() });
                                }
                            }
                        }
                    }
                });
            });
            client.on("error", (e) => {
                console.log(e);
            });
            client.on("end", () => {
            });
        });
    }
    ThreeWayCall(req, res, next, sessdata, lerg_data, vrate, callback) {
        let digit;
        digit = req.body.TONE;
        let client = new net_1.Socket();
        client.connect(parseInt(vs_server.PORT), vs_server.HOST, () => {
            console.log('CONNECTED TO: ' + vs_server.HOST + ':' + vs_server.PORT);
            client.write('auth ' + vs_server.PASS + '\n\n');
            console.log("Password : " + vs_server.PASS);
            client.write("api originate {effective_caller_id_name=+14233016767,effective_caller_id_number=+14233016767,origination_caller_id_name=+14233016767,origination_caller_id_number=+14233016767,ocn=" + lerg_data[0].ocn + ",category=" + lerg_data[0].category + ",mobility=" + lerg_data[0].co_name_spec_c + ",idapi=' + sessdata.idapi + ',leg_other=" + vrate.getCallRate(req.body.Number) + "}sofia/gateway/iplink/" + prefix + req.body.Number + " XML default");
            console.log("api originate {effective_caller_id_name=+14233016767,effective_caller_id_number=+14233016767,origination_caller_id_name=+14233016767,origination_caller_id_number=+14233016767,ocn=" + lerg_data[0].ocn + ",category=" + lerg_data[0].category + ",mobility=" + lerg_data[0].co_name_spec_c + ",idapi=' + sessdata.idapi + ',leg_other=" + vrate.getCallRate(req.body.Number) + "}sofia/gateway/iplink/" + prefix + req.body.Number + " XML default");
            client.on("data", (respon) => {
                console.log("respon", respon.toString);
                let tmp = respon.toString().split("\n");
                console.log("tmp", tmp);
                tmp.forEach((elem) => {
                    console.log("elem", elem);
                    if (elem != undefined) {
                        if (elem.length > 0) {
                            console.log(elem);
                            let t1 = elem.split("OK");
                            console.log("t1", t1);
                            if (t1.length == 2) {
                                console.log(t1);
                                if (t1[0] == "+") {
                                    res.status(200).send(t1[1].trim());
                                    console.log("uuid_bridge" + req.body.UUID + " " + t1[1].trim());
                                    client.write("uuid_bridge" + req.body.UUID + " " + t1[1].trim());
                                    client.destroy();
                                }
                            }
                        }
                    }
                });
            });
            client.on("error", (e) => {
                console.log(e);
            });
            client.on("end", () => {
            });
        });
    }
    Barge(req, res, next, sessdata, lerg_data, vrate, callback) {
        req.body.FROM = "4233016767";
        let cmd = "api originate {effective_caller_id_name=" + req.body.FROM.trim() + ",effective_caller_id_number=" + req.body.FROM.trim() + ",origination_caller_id_name=" + req.body.FROM.trim() + ",origination_caller_id_number=" + req.body.FROM.trim() + ",leg_other=" + vrate.getCallRate(req.body.Number) + ",idapi=" + sessdata.idapi + ",ocn=" + lerg_data[0].ocn + ",category=" + lerg_data[0].category + ",mobility=" + lerg_data[0].co_name_spec_c + "}sofia/gateway/iplink/" + prefix + req.body.Number + " 88" + req.body.Extension + "";
        console.log(cmd);
        let client = new net_1.Socket();
        client.connect(parseInt(vs_server.PORT), vs_server.HOST, function () {
            console.log('CONNECTED TO: ' + vs_server.HOST + ':' + vs_server.PORT);
            client.write('auth ' + vs_server.PASS + '\n\n');
            console.log("Password : " + vs_server.PASS);
            client.write(cmd + '\n\n');
            client.on("data", (respon) => {
                let tmp = respon.toString().split("\n");
                tmp.forEach((elem) => {
                    if (elem != undefined) {
                        if (elem.length > 0) {
                            console.log(elem);
                            let t1 = elem.split("OK");
                            if (t1.length == 2) {
                                console.log(t1);
                                if (t1[0] == "+") {
                                    res.status(200).send(t1[1].trim());
                                    client.destroy();
                                }
                            }
                        }
                    }
                });
            });
            client.on("error", (e) => {
                console.log(e);
            });
            client.on("end", () => {
            });
        });
    }
    CallTransfer(req, res, next, sessdata, lerg_data, vrate, callback) {
        let length = req.body.Number.length;
        if (length == 7) {
            var socketData = req.body.UUID + " -bleg " + req.body.Number + " XML default";
        }
        else {
            var socketData = req.body.UUID.trim() + " -bleg 88791" + req.body.Number.trim() + " XML default";
        }
        let client = new net_1.Socket();
        client.connect(parseInt(vs_server.PORT), vs_server.HOST, function () {
            console.log('CONNECTED TO: ' + vs_server.HOST + ':' + vs_server.PORT);
            client.write('auth ' + vs_server.PASS + '\n\n');
            console.log("Password : " + vs_server.PASS);
            console.log(socketData);
            client.write('api uuid_transfer ' + socketData + '\n\n');
            client.on("data", (respon) => {
                let tmp = respon.toString().split("\n");
                tmp.forEach((elem) => {
                    if (elem != undefined) {
                        if (elem.length > 0) {
                            console.log(elem);
                            let t1 = elem.split("OK");
                            if (t1.length == 2) {
                                console.log(t1);
                                if (t1[0] == "+") {
                                    client.write("api uuid_setvar " + req.body.UUID + " leg_other " + vrate.getCallRate(req.body.Number) + '\n\n');
                                    res.status(200).send(t1[1].trim());
                                    client.destroy();
                                }
                            }
                        }
                    }
                });
            });
            client.on("error", (e) => {
                console.log("Error", e);
            });
            client.on("end", () => {
                console.log("End");
            });
        });
    }
    login(req, res, callback) {
        var options = {
            'method': 'POST',
            'url': 'https://apicontrol.call48.com/api/v4/login',
            'headers': {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'user_name': 'iplink1',
                "password": "kzwJQV4arc4",
            }),
        };
        request(options, (error, response) => {
            if (!error) {
                let sdata = JSON.parse(response.body);
                if (sdata.code == 200) {
                    let authkey = sdata.data.token;
                    callback('', authkey);
                }
                else {
                    callback(sdata, '');
                }
            }
            else {
                callback(error, '');
            }
        });
    }
}
exports.APIBase = APIBase;
