"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TeleAPI = void 0;
const APIBase_1 = require("./APIBase");
const RawNonQuery_1 = require("../lib/model/RawNonQuery");
const RawQuery_1 = require("../lib/model/RawQuery");
const numberApi_1 = require("./numberApi");
const RawView_1 = require("../lib/view/RawView");
var request = require('request');
class TeleAPI extends APIBase_1.APIBase {
    key;
    secret;
    priority;
    sessdata;
    timekey;
    constructor(proirity, sessdata, timekey) {
        super();
        this.key = "48de6c84-7726-4879-bc08-f7a5dcf63f1c";
        this.timekey = timekey,
            this.secret = "";
        this.priority = proirity;
        this.sessdata = sessdata;
    }
    getNpaNxx(req, res, callback) {
        if (this.priority == "100") {
            callback('', '');
        }
        else {
            this.getRate(req, res, this.sessdata.idtariff, "message", "NN", (err, voice_rate) => {
                if (err == 1 && voice_rate.length > 0) {
                    const sdata = req.query;
                    var options = {
                        'method': 'POST',
                        'url': 'https://apiv1.teleapi.net/dids/list?token=' + this.key + '&npa=' + `${sdata.NPA}` + '&limit=' + `${sdata.Qty}`,
                        'headers': {
                            'Content-Type': 'application/json'
                        }
                    };
                    request(options, (error, response) => {
                        let ddata = JSON.parse(response.body);
                        if (!error) {
                            if (ddata.code == 200) {
                                if (ddata.data.dids != undefined && ddata.data.dids.length > 0) {
                                    let str = ddata.data.dids;
                                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    let qrystr = "INSERT INTO `did_search` (`friendly_name`, `phone_number`, `lata`, `locality`, `rate_center`, `state`, `postal_code`, `capabilities` ,`city`, `provider`, `iduser`, `priorty`,`type`,`supplier_tier`,`supplier_rate`,`rates`,`camp_registry`,`path`,`idapi`,`key`) VALUE";
                                    str.forEach((ele) => {
                                        qrystr += "('','" + ele.number + "', '', '', '" + ele.ratecenter + "', '" + ele.state + "', '', '','', '" + "teleapi" + "', '" + this.sessdata.iduser + "', '" + this.priority + "','NN','" + ele.tier + "','nrc:" + ele.setup_rate + ",mrc:" + ele.monthly_rate + ",usage:" + ele.per_minute_rate + "','" + voice_rate[0].rate + "','" + sdata.CampaignId + "','" + this.sessdata.path + "','" + this.sessdata.idapi + "','" + this.timekey + "'),";
                                    });
                                    obj1.nonqrysql = qrystr.slice(0, -1);
                                    obj1.prepare();
                                    obj1.execute((err, data) => {
                                        callback(err, data);
                                    });
                                }
                                else {
                                    let obj = new RawView_1.RawView(res);
                                    obj.prepare({ message: "No DID's found on [" + sdata.NPA + "]" });
                                    obj.execute();
                                }
                            }
                            else {
                                callback('', ddata);
                            }
                        }
                        else {
                            callback(error, '');
                        }
                    });
                }
                else {
                    callback(err, voice_rate);
                }
            });
        }
    }
    getByRate(req, res, callback) {
        if (this.priority == "100") {
            callback('', '');
        }
        else {
            this.getRate(req, res, this.sessdata.idtariff, "message", "NN", (err, voice_rate) => {
                if (err == 1 && voice_rate.length > 0) {
                    const sdata = req.query;
                    var options = {
                        'method': 'POST',
                        'url': 'https://apiv1.teleapi.net/dids/list?token=' + this.key + '&state=' + `${sdata.State}` + '&ratecenter=' + `${sdata.RateCenter}` + '&limit=' + `${sdata.Qty}`,
                        'headers': {
                            'Content-Type': 'application/json'
                        }
                    };
                    request(options, (error, response) => {
                        let ddata = JSON.parse(response.body);
                        console.log("ddata", JSON.stringify(ddata));
                        if (!error) {
                            if (ddata.code == 200) {
                                if (ddata.data.dids != undefined && ddata.data.dids.length > 0) {
                                    let str = ddata.data.dids;
                                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    let qrystr = "INSERT INTO `did_search` (`friendly_name`, `phone_number`, `lata`, `locality`, `rate_center`, `state`, `postal_code`, `capabilities` ,`city`, `provider`, `iduser`, `priorty`,`type`,`supplier_tier`,`supplier_rate`,`rates`,`camp_registry`,`path`,`idapi`,`key`) VALUE";
                                    str.forEach((ele) => {
                                        qrystr += "('','" + ele.number + "', '', '', '" + ele.ratecenter + "', '" + ele.state + "', '', '','', '" + "teleapi" + "', '" + this.sessdata.iduser + "', '" + this.priority + "','NN','" + ele.tier + "','nrc:" + ele.setup_rate + ",mrc:" + ele.monthly_rate + ",usage:" + ele.per_minute_rate + "','" + voice_rate[0].rate + "','" + sdata.CampaignId + "','" + this.sessdata.path + "','" + this.sessdata.idapi + "','" + this.timekey + "'),";
                                    });
                                    obj1.nonqrysql = qrystr.slice(0, -1);
                                    obj1.prepare();
                                    obj1.execute((err, data) => {
                                        callback(err, data);
                                    });
                                }
                                else {
                                    callback('', ddata);
                                }
                            }
                            else {
                                callback('', ddata);
                            }
                        }
                        else {
                            callback(error, '');
                        }
                    });
                }
                else {
                    callback(err, voice_rate);
                }
            });
        }
    }
    getTollFree(req, res, callback) {
        if (this.priority == "100") {
            callback('', '');
        }
        else {
            this.getRate(req, res, this.sessdata.idtariff, "message", "TF", (err, voice_rate) => {
                if (err == 1 && voice_rate.length > 0) {
                    var sdata = req.query;
                    var options = {
                        'method': 'POST',
                        'url': 'https://apiv1.teleapi.net/dids/list?token=' + this.key + '&type=tollfree&limit=' + `${sdata.Qty}`,
                        'headers': {
                            'Content-Type': 'application/json'
                        }
                    };
                    request(options, (error, response) => {
                        let ddata = JSON.parse(response.body);
                        console.log("ddata", ddata);
                        console.log(ddata.code);
                        if (!error) {
                            if (ddata.code == 200) {
                                if (ddata.data.dids != undefined && ddata.data.dids.length > 0) {
                                    let str = ddata.data.dids;
                                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    let qrystr = "INSERT INTO `did_search` (`friendly_name`, `phone_number`, `lata`, `locality`, `rate_center`, `state`, `postal_code`, `capabilities` ,`city`, `provider`, `iduser`, `priorty`,`type`,`supplier_tier`,`supplier_rate`,`rates`,`path`,`idapi`,`key`) VALUE";
                                    str.forEach((ele) => {
                                        qrystr += "('','" + ele.number + "', '', '', '', '', '', '','', '" + "teleapi" + "', '" + this.sessdata.iduser + "', '" + this.priority + "','TF','','nrc:" + ele.setup_rate + ",mrc:" + ele.monthly_rate + ",usage:" + ele.per_minute_rate + "','" + voice_rate[0].rate + "','" + this.sessdata.path + "','" + this.sessdata.idapi + "','" + this.timekey + "'),";
                                    });
                                    obj1.nonqrysql = qrystr.slice(0, -1);
                                    obj1.prepare();
                                    obj1.execute((err, data) => {
                                        callback(err, data);
                                    });
                                }
                                else {
                                    callback('', ddata);
                                }
                            }
                            else {
                                callback('', ddata);
                            }
                        }
                        else {
                            callback(error, '');
                        }
                    });
                }
                else {
                    callback(err, voice_rate);
                }
            });
        }
    }
    buyDID(req, res, did_details, other_data, callback) {
        const sdata = req.body;
        let types;
        let did = sdata.DID.trim();
        let len = did.length - 10;
        let npa = did.slice(len, len + 3);
        let nxx = did.slice(len + 3, len + 6);
        let id_grouporder = other_data.id_grouporder;
        this.getRateCenter(req, res, npa, nxx, (err, ratecenter_state) => {
            let ratecenter = ratecenter_state[0] !== undefined ? ratecenter_state[0].rc_abbre : '';
            let state = ratecenter_state[0] !== undefined ? ratecenter_state[0].loc_state : '';
            // To get the proration status
            let objv0 = new RawQuery_1.ModelRawQuery(req, res);
            objv0.qrysql = "SELECT t.proration FROM `user`u JOIN `tariff`t ON u.idtariff=t.idtariff WHERE iduser= '" + this.sessdata.iduser + "'";
            objv0.prepare();
            objv0.execute((proration_error, proration_success) => {
                if (proration_error == 1) {
                    let proration_status = proration_success[0].proration;
                    types = did_details[0].type == 'TF' ? 'TF' : 'NN';
                    var options = {
                        'method': 'POST',
                        'url': 'https://apiv1.teleapi.net/dids/order?token=' + this.key + '&number=' + `${sdata.DID.trim()}`,
                        'headers': {
                            'Content-Type': 'application/json'
                        }
                    };
                    request(options, (error, response) => {
                        console.log("TeleAPI::", response.body);
                        let sdata1 = JSON.parse(response.body);
                        if (!error) {
                            // If order successfully placed
                            if (sdata1.code == 200 && sdata1.status == 'success') {
                                let providerOrderId = typeof sdata1.data.id != 'undefined' && sdata1.data.id ? sdata1.data.id : '';
                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj.nonqrysql = "INSERT INTO `did_buy` (`npa`,`nxx`,`ratecenter`,`state`,`account_id`, `user_id`, `status`, `did`,`provider`,`order_id`,`type`,`iduser`,`disconnect_did_status`,`inbound_key`,`outbound_key`,`connection_key`,`sms_inbound_key`,`sms_outbound_key`,`rates`,`camp_registry`,`idapi`,`sms_provider`) VALUE('" + npa + "','" + nxx + "','" + ratecenter + "','" + state + "','" + this.sessdata.idaccount + "','" + sdata1.data.user_id + "','completed','" + sdata1.data.number + "','teleapi','" + sdata1.data.id + "','" + types + "','" + this.sessdata.iduser + "','1','" + sdata.InboundVoice + "','" + sdata.OutboundVoice + "','" + sdata.Connection + "','" + sdata.InboundSMS + "','" + sdata.OutboundSMS + "','" + did_details[0].rates + "','" + sdata.CampaignId + "','" + this.sessdata.idapi + "','teleapi')";
                                obj.prepare();
                                obj.execute((err, data) => {
                                    if (err == 1) {
                                        let dateObj = new Date();
                                        let day = dateObj.getUTCDate();
                                        let nDate = new Date();
                                        let lDate = (new Date(nDate.getFullYear(), (nDate.getMonth() + 1), 0)).getDate();
                                        let totalDays = (lDate - day) + 1;
                                        let prorate;
                                        if (proration_status == "true") {
                                            prorate = (totalDays * did_details[0].rates) / 30;
                                        }
                                        else {
                                            prorate = did_details[0].rates;
                                        }
                                        console.log(prorate);
                                        let objv = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        objv.nonqrysql = "UPDATE `wallet` SET `balance`=`balance`-" + prorate + " WHERE `idaccount`='" + this.sessdata.idaccount + "'";
                                        objv.prepare();
                                        objv.execute((wallet_error, wallet_success) => {
                                            // To update the wallet transaction log
                                            let iQry = "INSERT INTO `wallet_recharge_log` SET ";
                                            iQry += "`idaccount`=" + this.sessdata.idaccount + ", ";
                                            iQry += "`amount`='-" + prorate + "', ";
                                            iQry += "`purpose`='Wallet amount successfully updated for buy a new DID', ";
                                            iQry += "`status`=1;";
                                            let objWL = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            objWL.nonqrysql = iQry;
                                            objWL.prepare();
                                            objWL.execute((error, result) => {
                                                console.log("Transaction response::", result);
                                            });
                                            // To create the DID log
                                            let objv1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            objv1.nonqrysql = "INSERT INTO `did_log` (`account_id`, `user_id`, `status`, `did`,`provider`,`order_id`,`type`,`iduser`,`disconnect_did_status`,`npa`,`nxx`,`state`,`ratecenter`,`rates`,`idapi`,`pro_rates`) VALUE('" + this.sessdata.idaccount + "','','completed','" + sdata1.data.number + "','teleapi','" + sdata1.data.id + "','" + types + "','" + this.sessdata.iduser + "','1','" + npa + "','" + nxx + "','" + state + "','" + ratecenter + "','" + did_details[0].rates + "','" + this.sessdata.idapi + "','" + prorate + "')";
                                            objv1.prepare();
                                            objv1.execute((log_error, did_log) => { });
                                            // To delete the DID from cart
                                            let obj5 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            obj5.nonqrysql = "DELETE FROM `did_cart` WHERE did='" + sdata.DID + "'";
                                            obj5.prepare();
                                            obj5.execute((walletError, wallet) => { });
                                            // To create the did_order
                                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            obj.nonqrysql = "INSERT INTO `did_order` (`iduser`, `idaccount`, `status`, `did`, `error_code`, `type`, `cost`, `description`, `id_grouporder`, `is_process`) VALUE('" + this.sessdata.iduser + "', '" + this.sessdata.idaccount + "', '201','" + sdata.DID + "', '2', '" + types + "', '" + did_details[0].rates + "', 'Order successfully created.', " + id_grouporder + ", 1)";
                                            obj.prepare();
                                            obj.execute((did_err, did_data) => {
                                                // To update the other data on current order
                                                if (did_err == 1) {
                                                    let id_order = did_data.insertId;
                                                    let orderID = "SORD" + id_order.toString();
                                                    let log_error = "";
                                                    let log_message = sdata1.status.replace(/'/g, "\\'").replace(/"/g, '\\"');
                                                    let log_result = JSON.stringify(sdata1).replace(/'/g, "\\'").replace(/"/g, '\\"');
                                                    obj.nonqrysql = "UPDATE `did_order` SET `order_no`='" + orderID + "', `log_statusCode`='200', `log_error`='" + log_error + "', `log_message`='" + log_message + "', `log_result`='" + log_result + "', `log_status`=0, `provider`='teleapi', `providerOrderId`='" + providerOrderId + "' WHERE `id_order`=" + id_order + ";";
                                                    obj.prepare();
                                                    obj.execute((error, result) => { });
                                                }
                                                let objV = new RawView_1.RawView(res);
                                                objV.prepare({
                                                    error_code: 1,
                                                    status: 201,
                                                    message: "DID buy successfully.",
                                                    result: [
                                                        {
                                                            "did": sdata.DID
                                                        }
                                                    ]
                                                });
                                                objV.execute();
                                            });
                                        });
                                    }
                                    else {
                                        let obj = new RawView_1.RawView(res);
                                        obj.prepare({
                                            error_code: 0,
                                            status: 502,
                                            message: "Something went wrong with connection"
                                        });
                                        obj.execute();
                                    }
                                });
                            }
                            // If order failed
                            else {
                                let providerOrderId = typeof sdata1.data.id != 'undefined' && sdata1.data.id ? sdata1.data.id : '';
                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj.nonqrysql = "INSERT INTO `did_order` (`iduser`, `idaccount`, `status`, `did`, `error_code`, `type`, `cost`, `description`, `id_grouporder`, `is_process`) VALUE('" + this.sessdata.iduser + "', '" + this.sessdata.idaccount + "', '501', '" + sdata.DID + "', '4', '" + types + "', '" + did_details[0].rates + "', 'Order creation failed!', " + id_grouporder + ", 1)";
                                obj.prepare();
                                obj.execute((did_err, did_data) => {
                                    // To update the other data on current order
                                    if (did_err == 1) {
                                        let id_order = did_data.insertId;
                                        let orderID = "SORD" + id_order.toString();
                                        let log_error = JSON.stringify(sdata1).replace(/'/g, "\\'").replace(/"/g, '\\"');
                                        let log_message = sdata1.data.replace(/'/g, "\\'").replace(/"/g, '\\"');
                                        let log_result = "";
                                        obj.nonqrysql = "UPDATE `did_order` SET `order_no`='" + orderID + "', `log_statusCode`='" + sdata1.code + "', `log_error`='" + log_error + "', `log_message`='" + log_message + "', `log_result`='" + log_result + "', `log_status`=1, `provider`='teleapi', `providerOrderId`='" + providerOrderId + "' WHERE `id_order`=" + id_order + ";";
                                        obj.prepare();
                                        obj.execute((error, result) => { });
                                    }
                                    let objV = new RawView_1.RawView(res);
                                    objV.prepare({
                                        error_code: 0,
                                        status: sdata1.code,
                                        message: sdata1.data,
                                        error: sdata1
                                    });
                                    objV.execute();
                                });
                            }
                        }
                        else {
                            let obj = new RawView_1.RawView(res);
                            obj.prepare({
                                error_code: 0,
                                status: 400,
                                error: error
                            });
                            obj.execute();
                        }
                    });
                }
                else {
                    let obj = new RawView_1.RawView(res);
                    obj.prepare({
                        error_code: 0,
                        status: 502,
                        message: "Something went wrong with get proration!"
                    });
                    obj.execute();
                }
            });
        });
    }
    disconnectDID(req, res, callback) {
        const sdata = req.body;
        let iduser = (typeof sdata.iduser != 'undefined' && sdata.iduser > 0) ? sdata.iduser : this.sessdata.iduser;
        let obj1 = new RawQuery_1.ModelRawQuery(req, res);
        obj1.qrysql = "SELECT `day_num` from `tariff` WHERE `idtariff`='" + this.sessdata.idtariff + "'";
        obj1.prepare();
        obj1.execute((errday, resday) => {
            if (errday == 1 && resday.length > 0) {
                let number = new numberApi_1.Number();
                number.countDays(req, res, sdata.DID.trim(), (err, countdays) => {
                    if (countdays && countdays > resday[0].day_num) {
                        let obj5 = new RawQuery_1.ModelRawQuery(req, res);
                        obj5.qrysql = "SELECT `type` from `did_buy` WHERE `iduser`='" + iduser + "' AND `did`='" + sdata.DID.trim() + "'";
                        obj5.prepare();
                        obj5.execute((err, ress) => {
                            if (err == 1 && ress.length > 0) {
                                var options = {
                                    'url': 'https://apiv1.teleapi.net/user/dids/remove?token=' + this.key + '&number=' + `${sdata.DID.trim()}`,
                                    'headers': {
                                        'Content-Type': 'application/json'
                                    }
                                };
                                request(options, (error, response) => {
                                    console.log("TeleAPI Err::", error);
                                    if (!error) {
                                        console.log("TeleAPI Res::", response.body);
                                        let data = JSON.parse(response.body);
                                        if (data.code == 200) {
                                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            obj.nonqrysql = "UPDATE `did_buy` set `disconnect_did_status`='3',`updated_at`=NOW() WHERE `did`='" + sdata.DID.trim() + "'AND `iduser`='" + iduser + "'";
                                            obj.prepare();
                                            obj.execute((error, resp) => {
                                                if (error == 1) {
                                                    // To  update updated_at date in did log
                                                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                    obj.nonqrysql = "UPDATE `did_log` SET `updated_at`=NOW(), `disconnect_did_status`='3' WHERE `did`='" + sdata.DID.trim() + "' AND `iduser`='" + iduser + "' ORDER BY `iddidlog` DESC LIMIT 1";
                                                    obj.prepare();
                                                    obj.execute((errorDiDLg, resDiDLg) => { });
                                                    let objv = new RawView_1.RawView(res);
                                                    objv.prepare({ status: 201, message: "DID Disconnected Successfully" });
                                                    objv.execute();
                                                }
                                                else {
                                                    let objv = new RawView_1.RawView(res);
                                                    objv.prepare({ status: 502, message: "Something went wrong with connection!" });
                                                    objv.execute();
                                                }
                                            });
                                        }
                                        else {
                                            let objv = new RawView_1.RawView(res);
                                            objv.prepare({ status: data.code, message: data.status, error: data.data });
                                            objv.execute();
                                        }
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ status: 400, error: error });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ status: 502, message: "Something went wrong with connection!" });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ status: 417, message: "Days are Less then " + resday[0].day_num + " So you can not disconnect Did from this Account" });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ status: 502, message: "Days Not Found!" });
                objv.execute();
            }
        });
    }
}
exports.TeleAPI = TeleAPI;
