"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OsrApi = void 0;
const RawNonQuery_1 = require("../lib/model/RawNonQuery");
const RawQuery_1 = require("../lib/model/RawQuery");
const numberRegistry_1 = require("../include/numberRegistry");
const SinchSubmitNumber_1 = require("../include/SinchSubmitNumber");
const RawView_1 = require("../lib/view/RawView");
const cron = require('node-cron');
let request = require('request');
const produrl = 'http://65.214.42.91:84/osr/v2/entries/';
const devurl = 'http://osrdev-e1.netnumber.net:84/osr/v2/entries/';
const myip = "iplink";
const nnid = "104141";
class OsrApi extends numberRegistry_1.NumberRegistry {
    constructor(proirity, sessdata) {
        super(proirity, sessdata);
    }
    /**
     * To Add entry into OSR :: first method
     */
    addNumber(req, res, callback) {
        let sdata = req.body;
        let did = sdata.DID;
        let len = did.length - 10;
        let number = did.slice(len, did.length);
        let number1 = "+1" + number;
        let options = {
            'method': 'PUT',
            'url': produrl + "" + `${number1}`,
            'headers': {
                'Content-Type': 'application/json'
            },
            body: '{id:"' + myip + '", nnid: "' + nnid + '"}'
        };
        console.log("options", options);
        request(options, (error, response) => {
            if (!error) {
                let data = JSON.parse(response.body);
                if (data.message == "Success") {
                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj.nonqrysql = "UPDATE `did_buy` SET `osr_status` = 'register' where `iduser` = '" + this.sessdata.iduser + "' AND `did`='" + number + "'";
                    obj.prepare();
                    obj.execute((err, resp) => {
                        if (resp) {
                            if (sdata.CampaignId !== undefined) {
                            }
                            else {
                                let obj = new RawView_1.RawView(res);
                                obj.prepare({ status: 201, message: "DID buy and SMS enabled successfully" });
                                obj.execute();
                            }
                        }
                        return callback(err, '');
                    });
                }
            }
            else {
                callback(error, "");
            }
        });
    }
    /**
     * To Update entry into OSR :: first method
     */
    updateNumber(req, res, did_id, callback) {
        let sdata = req.body;
        let did = sdata.DID.trim();
        let len = did.length - 10;
        let number = did.slice(len, did.length);
        let number1 = "+1" + number;
        if (sdata.CampaignId != null && sdata.CampaignId != '') {
            let objc = new RawQuery_1.ModelRawQuery(req, res);
            objc.qrysql = "SELECT `myip`, `nnid`, `sms_provider` FROM `osr_nnid` WHERE `sms_provider`=(SELECT upstreamCnpId FROM `campaign` WHERE `campaign_key`='" + sdata.CampaignId + "' AND `deleted`=0 LIMIT 1)";
            objc.prepare();
            objc.execute((camp_err, camp_result) => {
                if (camp_err == 1 && camp_result.length > 0) {
                    let options = {
                        'method': 'PUT',
                        'url': produrl + "" + `${number1}`,
                        'headers': {
                            'Content-Type': 'application/json'
                        },
                        body: '{ id: "' + camp_result[0].myip + '", nnid:"' + camp_result[0].nnid + '" , "context": "A2P", "campaign_id": "' + sdata.CampaignId + '" }'
                    };
                    request(options, (error, response) => {
                        if (!error) {
                            let data = JSON.parse(response.body);
                            if (data.message == "Success") {
                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj.nonqrysql = "UPDATE `did_buy` SET `osr_status` = 'register', `sms_provider`='" + camp_result[0].sms_provider + "' WHERE `iduser` = '" + this.sessdata.iduser + "' AND `did`='" + number + "'";
                                obj.prepare();
                                obj.execute((err, resp) => { });
                                let objV = new RawView_1.RawView(res);
                                objV.prepare({
                                    error_code: 1,
                                    status: 201,
                                    message: "DID Buy and OSR Submitted Successfully.",
                                    result: [
                                        {
                                            "did": number
                                        }
                                    ]
                                });
                                objV.execute();
                            }
                            else {
                                let obj = new RawView_1.RawView(res);
                                obj.prepare({
                                    error_code: 1,
                                    status: 400,
                                    message: "DID Buy Successfully but OSR Submission Failed!",
                                    result: [
                                        {
                                            "did": number
                                        }
                                    ],
                                    error: data
                                });
                                obj.execute();
                            }
                        }
                        else {
                            let obj = new RawView_1.RawView(res);
                            obj.prepare({
                                error_code: 1,
                                status: 400,
                                message: "DID Buy Successfully but OSR Submission Failed!",
                                result: [
                                    {
                                        "did": number
                                    }
                                ],
                                error: error
                            });
                            obj.execute();
                        }
                    });
                }
                else {
                    let obj = new RawView_1.RawView(res);
                    obj.prepare({
                        error_code: 1,
                        status: 400,
                        message: "DID Buy Successfully but OSR Submission Failed!",
                        result: [
                            {
                                "did": number
                            }
                        ],
                        error: "Campaign Not found!"
                    });
                    obj.execute();
                }
            });
        }
        else {
            let obj = new RawView_1.RawView(res);
            obj.prepare({
                error_code: 1,
                status: 400,
                message: "DID Buy Successfully but OSR Submission Failed!",
                result: [
                    {
                        "did": number
                    }
                ],
                error: "Campaign Not found!"
            });
            obj.execute();
        }
    }
    /**
     * To Update entry with toll-free provisioning into OSR :: first method
     */
    updateNumberWithTollfree(req, res, callback) {
        let sdata = req.body;
        let options = {
            'method': 'PUT',
            'url': 'https://208.254.45.98/osr/v2/entries/1800551212',
            'headers': {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ "id": "mypid", "nnid": "123456", "context": "A2P", "ownertspid": "3434" })
        };
        request(options, (error, response) => {
            if (!error) {
                let ddata = JSON.parse(response.body);
                if (ddata.rows.length > 0) {
                }
                else {
                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj.prepare();
                    obj.execute((err, data) => {
                        callback(err, data);
                    });
                }
            }
            else {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.prepare();
                obj.execute((err, data) => {
                    callback(err, data);
                });
            }
        });
    }
    /**
     * To Delete entry from OSR And Then SINCH :: first method
     */
    deleteNumber(req, res, callback) {
        let sdata = req.query;
        let did = sdata.DID.trim();
        let len = did.length - 10;
        let number = did.slice(len, did.length);
        let number1 = "+1" + number;
        let obj0 = new RawQuery_1.ModelRawQuery(req, res);
        obj0.qrysql = "SELECT `camp_registry` FROM `did_buy` WHERE `did`='" + number + "' AND `iduser` = '" + this.sessdata.iduser + "'";
        obj0.prepare();
        obj0.execute((err, result_did) => {
            if (err == 1 && result_did.length > 0) {
                let obj00 = new RawQuery_1.ModelRawQuery(req, res);
                obj00.qrysql = "SELECT `did_count`, `did_limit`, campaign_key, campaign_name FROM `campaign` WHERE `iduser`='" + this.sessdata.iduser + "' AND `campaign_key`='" + result_did[0].camp_registry + "' GROUP BY campaign_key";
                obj00.prepare();
                obj00.execute((err, result_camp) => {
                    if (err == 1 && result_camp.length > 0) {
                        let obj00 = new RawQuery_1.ModelRawQuery(req, res);
                        obj00.qrysql = "SELECT `iddidlog` FROM did_log WHERE `did`= '" + sdata.DID.trim() + "' AND `iduser` = '" + this.sessdata.iduser + "' ORDER BY `iddidlog` DESC";
                        obj00.prepare();
                        obj00.execute((log_error, log_res) => {
                            if (log_error == 1 && log_res.length > 0) {
                                let options = {
                                    'method': 'DELETE',
                                    'url': produrl + "" + `${number1}`,
                                    'headers': {
                                        'Content-Type': 'application/json'
                                    },
                                    body: '{id:"' + myip + '", nnid: "' + nnid + '"}'
                                };
                                request(options, (error, response) => {
                                    if (!error) {
                                        let data = JSON.parse(response.body);
                                        if (data.message == "Success") {
                                            // Counting Decrease (-1) and status update
                                            let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            obj1.nonqrysql = "UPDATE `campaign` SET did_count=(" + result_camp[0].did_count + "-1) WHERE `iduser` = '" + this.sessdata.iduser + "' AND campaign_key = '" + result_camp[0].campaign_key + "'";
                                            obj1.prepare();
                                            obj1.execute((err, updt_didby) => { });
                                            let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            obj2.nonqrysql = "UPDATE `did_buy` SET `osr_status` = 'unregister',`sms_provider` = '',`camp_registry` = '' where `iduser` = '" + this.sessdata.iduser + "' AND `did`='" + number + "'";
                                            obj2.prepare();
                                            obj2.execute((uperr, updt_stts) => {
                                                let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                obj3.nonqrysql = "INSERT INTO `campaign_history`(`iduser`,`idaccount`,`did`,`campaign_key`,`campaign_name`,`in_use`,`iddidlog`) VALUES ('" + this.sessdata.iduser + "','" + this.sessdata.idaccount + "','" + number + "','" + result_camp[0].campaign_key + "','" + result_camp[0].campaign_name + "', '1','" + log_res[0].iddidlog + "')";
                                                obj3.prepare();
                                                obj3.execute((err, ins_res) => {
                                                    if (err == 1) {
                                                        // Delete from sinch
                                                        let sinch = new SinchSubmitNumber_1.SinchApi('', this.sessdata);
                                                        sinch.deleteNumber(req, res, (errorr, resp) => {
                                                            if (!errorr) {
                                                                let obj1 = new RawView_1.RawView(res);
                                                                obj1.prepare({ status: 201, message: "DID Disabled Successfully From OSR and SINCH.", result: resp });
                                                                obj1.execute();
                                                            }
                                                            else {
                                                                let obj = new RawView_1.RawView(res);
                                                                obj.prepare({ status: 400, error: errorr });
                                                                obj.execute();
                                                            }
                                                        });
                                                    }
                                                    else {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({ status: 502, message: 'Data Not Updated Successfully!' });
                                                        objv.execute();
                                                    }
                                                });
                                            });
                                        }
                                        else {
                                            let obj = new RawView_1.RawView(res);
                                            obj.prepare({ status: data.response_code, message: data.message, result: data });
                                            obj.execute();
                                        }
                                    }
                                    else {
                                        let obj = new RawView_1.RawView(res);
                                        obj.prepare({ status: 400, error: error });
                                        obj.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ status: 404, message: `ID DID not found on this DID!` });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ status: 502, message: 'Campaign Registry Does not Match!' });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ status: 502, message: 'DID Not Available!' });
                objv.execute();
            }
        });
    }
    /**
     * To retrieve entry from OSR :: first method
     */
    retrieveOsrEntry(req, res, callback) {
        let sdata = req.query;
        let did = sdata.DID.trim();
        let len = did.length - 10;
        let number = did.slice(len, did.length);
        let number1 = "1" + number;
        let options = {
            'method': 'GET',
            'url': produrl + "" + number1 + "?id=" + myip,
            'headers': {
                'Content-Type': 'application/json'
            }
        };
        console.log("options", options);
        request(options, (error, response) => {
            if (!error) {
                let data = JSON.parse(response.body);
                if (data.message == "Success") {
                    let obj = new RawView_1.RawView(res);
                    obj.prepare({ status: 200, message: "OSR Details Find Successfully", result: data });
                    obj.execute();
                }
                else {
                    let obj = new RawView_1.RawView(res);
                    obj.prepare({ status: data.response_code, message: data.message, result: data });
                    obj.execute();
                }
            }
            else {
                let obj = new RawView_1.RawView(res);
                obj.prepare({ status: 400, result: error });
                obj.execute();
            }
        });
    }
    /**
     * To retrieve notification from OSR :: first method
     */
    retrieveOsrNotifications(req, res, callback) {
        let sdata = req.query;
        let options = {
            'method': 'GET',
            'url': "http://65.214.42.91:84/osr/v2/notifications?id=" + myip + "&tid=" + sdata.TID,
            'headers': {
                'Content-Type': 'application/json'
            }
        };
        console.log("options", options);
        request(options, (error, response) => {
            if (!error) {
                let data = JSON.parse(response.body);
                console.log("Data", data);
                let obj = new RawView_1.RawView(res);
                obj.prepare({ status: 200, message: "OSR Details Find Successfully", result: data });
                obj.execute();
            }
            else {
                let obj = new RawView_1.RawView(res);
                obj.prepare({ status: 400, result: error });
                obj.execute();
            }
        });
    }
    /**
     * To Delete entry from OSR :: second method
     */
    deleteNumberM2(req, res, payLoad, callback) {
        let did = payLoad.DID;
        let len = did.length - 10;
        let number = did.slice(len, did.length);
        let number1 = "+1" + number;
        let options = {
            'method': 'DELETE',
            'url': produrl + "" + `${number1}`,
            'headers': {
                'Content-Type': 'application/json'
            },
            body: '{id:"' + myip + '", nnid: "' + nnid + '"}'
        };
        request(options, (error, response) => {
            if (!error) {
                let data = JSON.parse(response.body);
                if (data.message == "Success") {
                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj.nonqrysql = "UPDATE `did_buy` SET `osr_status`='unregister', `disconnect_did_status`='4' WHERE `iduser`='" + this.sessdata.iduser + "' AND `did`='" + number + "';";
                    obj.prepare();
                    obj.execute((err, resp) => {
                        if (err == 1) {
                            callback(1, resp);
                        }
                        else {
                            callback(0, err);
                        }
                    });
                }
                else {
                    callback(0, data);
                }
            }
            else {
                callback(0, error);
            }
        });
    }
}
exports.OsrApi = OsrApi;
