"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SinchApi = void 0;
const RawNonQuery_1 = require("../lib/model/RawNonQuery");
const sinchNumberRegistry_1 = require("../include/sinchNumberRegistry");
const RawView_1 = require("../lib/view/RawView");
let request = require('request');
const produrl = 'http://65.214.42.91:84/osr/v2/entries/';
const projectId = "bd6ca3f8-040c-4b40-ba6c-09f8d63be111";
const servicePlanId = "IP_LINK_RA";
const userId = "f0c489dd-2203-4dc9-964a-c59021b9ee74";
const passwd = "Ew6Ynk~ddXD2UqmoHxWywDczB_";
const myip = "iplink";
const nnid = "104141";
class SinchApi extends sinchNumberRegistry_1.SinchNumberRegistry {
    constructor(proirity, sessdata) {
        super(proirity, sessdata);
    }
    /**
     * To Add entry into Sinch :: first method
     */
    submitNumber(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;
        var headers = {
            'accept': '*/*',
            'Accept': 'application/json'
        };
        var dataString = '{"phone_number":' + number1 + ', "projectId":' + projectId + ', "region_code":"US", "smsConfiguration":{"servicePlanId":' + servicePlanId + ', "campaignId":' + sdata.CampaignId + '}}';
        var options = {
            url: 'https://imported.numbers.api.sinch.com/v1beta1/projects/' + projectId + '/importedNumbers',
            method: 'POST',
            headers: headers,
            body: dataString,
            auth: {
                'user': userId,
                'pass': passwd
            }
        };
        request(options, (error, response) => {
            if (!error) {
                let data = JSON.parse(response.body);
                if (data.status == "WAITING") {
                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj.nonqrysql = "UPDATE `did_buy` SET `sinch_status` = 'register' where `iduser` = '" + this.sessdata.iduser + "' AND `did`='" + number + "'";
                    obj.prepare();
                    obj.execute((err, resp) => {
                        if (resp) {
                            let obj = new RawView_1.RawView(res);
                            obj.prepare({});
                            obj.execute();
                        }
                        else {
                            let obj = new RawView_1.RawView(res);
                            obj.prepare({ "error": "Query Error", "err": err });
                            obj.execute();
                        }
                    });
                }
                else if (data.status == "FAILED") {
                    this.updateNumber(req, res, (err, res) => {
                        if (res) {
                        }
                        else {
                        }
                    });
                }
            }
            else {
                callback(error, "");
            }
        });
    }
    /**
     * To Update entry into Sinch :: first method
     */
    updateNumber(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;
        var headers = {
            'accept': '*/*',
            'Accept': 'application/json'
        };
        var dataString = '{"phone_number":"' + number1 + '", "projectId":"' + projectId + '", "region_code":"US", "smsConfiguration":{"servicePlanId":"' + servicePlanId + '", "campaignId":"' + sdata.CampaignId + '"}}';
        var options = {
            url: 'https://imported.numbers.api.sinch.com/v1beta1/projects/' + projectId + '/importedNumbers/' + number1,
            method: 'PATCH',
            headers: headers,
            body: dataString,
            auth: {
                'user': userId,
                'pass': passwd
            }
        };
        request(options, (error, response) => {
            if (!error) {
                let data = JSON.parse(response.body);
                if (data.status == "WAITING") {
                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj.nonqrysql = "UPDATE `did_buy` SET `sinch_status` = 'register' where `iduser` = '" + this.sessdata.iduser + "' AND `did`='" + number + "'";
                    obj.prepare();
                    obj.execute((err, resp) => {
                        if (resp) {
                            let obj = new RawView_1.RawView(res);
                            obj.prepare({});
                            obj.execute();
                        }
                        else {
                            let obj = new RawView_1.RawView(res);
                            obj.prepare({ "error": "Query Error", "err": err });
                            obj.execute();
                        }
                    });
                }
            }
            else {
                callback(error, "");
            }
        });
    }
    /**
     * To Delete entry from Sinch  :: first method
     */
    deleteNumber(req, res, callback) {
        let sdata = req.query;
        let did = sdata.DID;
        let len = did.length - 10;
        let number = did.slice(len, did.length);
        let number1 = "1" + number;
        // let obj0 = new ModelRawQuery(req, res);
        // obj0.qrysql = "SELECT `camp_registry` FROM `did_buy` WHERE `did`='" + number + "' AND `iduser` = '" + this.sessdata.iduser + "'";
        // obj0.prepare();
        // obj0.execute((err: any, result_did: any) => {
        // if (err == 1 && result_did.length > 0) {
        var headers = {
            'accept': '*/*',
            'Accept': 'application/json'
        };
        var options = {
            url: 'https://imported.numbers.api.sinch.com/v1beta1/projects/' + projectId + '/importedNumbers/' + number1,
            method: 'GET',
            headers: headers,
            auth: {
                'user': userId,
                'pass': passwd
            }
        };
        request(options, (error, response) => {
            if (!error) {
                let data = JSON.parse(response.body);
                if (data.status == 200) {
                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj1.nonqrysql = "UPDATE `did_buy` SET `sinch_status` = '0' WHERE iduser = '" + this.sessdata.iduser + "' AND `did`='" + number + "'";
                    obj1.prepare();
                    obj1.execute((err, resp) => {
                        if (err == 1) {
                            let obj = new RawView_1.RawView(res);
                            obj.prepare({ status: 202, message: "DID Successfully Disabled." });
                            obj.execute();
                        }
                        else {
                            let obj = new RawView_1.RawView(res);
                            obj.prepare({ status: 502, message: "DID Disabled Successfully But Something Went Wrong With Data Update!" });
                            obj.execute();
                        }
                    });
                }
                else {
                    callback('', data);
                }
            }
            else {
                callback(error, '');
            }
        });
        //     }
        //     else {
        //         let objv = new RawView(res);
        //         objv.prepare({ status: 502, message: 'DID Not Available!' });
        //         objv.execute()
        //     }
        // });
    }
    // public deleteNumber(req: Request, res: Response, callback: (err: any, data: any) => void) {
    //     let sdata: any = req.query;
    //     let did = sdata.DID;
    //     let len = did.length - 10;
    //     let number = did.slice(len, did.length);
    //     let number1 = "1" + number;
    //     let obj0 = new ModelRawQuery(req, res);
    //     obj0.qrysql = "SELECT `camp_registry` FROM `did_buy` WHERE `did`='" + number + "' AND `iduser` = '" + this.sessdata.iduser + "'";
    //     obj0.prepare();
    //     obj0.execute((err: any, result_did: any) => {
    //         if (err == 1 && result_did.length > 0) {
    //             let obj00 = new 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: any, result_camp: any) => {
    //                 if (err == 1 && result_camp.length > 0) {
    //                     let obj00 = new 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: any, log_res: any) => {
    //                         if (log_error == 1 && log_res.length > 0) {
    //                             var headers = {
    //                                 'accept': '*/*',
    //                                 'Accept': 'application/json'
    //                             };
    //                             var options = {
    //                                 url: 'https://imported.numbers.api.sinch.com/v1beta1/projects/' + projectId + '/importedNumbers/' + number1,
    //                                 method: 'GET',
    //                                 headers: headers,
    //                                 auth: {
    //                                     'user': userId,
    //                                     'pass': passwd
    //                                 }
    //                             };
    //                             request(options, (error: any, response: any) => {
    //                                 if (!error) {
    //                                     let data = JSON.parse(response.body);
    //                                     if (data.status == 200) {
    //                                         let obj1 = new ModelRawNonQuery(req, res);
    //                                         obj1.nonqrysql = "UPDATE `did_buy` SET `sinch_status` = '0',`camp_registry` = '' WHERE iduser = '" + this.sessdata.iduser + "' AND `did`='" + number + "'";
    //                                         obj1.prepare();
    //                                         obj1.execute((err, resp) => {
    //                                             let obj2 = new ModelRawNonQuery(req, res);
    //                                             obj2.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 + "')";
    //                                             obj2.prepare();
    //                                             obj2.execute((err, resp) => {
    //                                                 if (err == 1) {
    //                                                     let obj = new RawView(res);
    //                                                     obj.prepare({ status: 202, message: "DID Successfully Disabled." });
    //                                                     obj.execute();
    //                                                 }
    //                                                 else {
    //                                                     let obj = new RawView(res);
    //                                                     obj.prepare({ status: 502, message: "DID Disabled Successfully But Something Went Wrong With Data Update!" });
    //                                                     obj.execute()
    //                                                 }
    //                                             });
    //                                         });
    //                                     } else {
    //                                         callback('', data);
    //                                     }
    //                                 } else {
    //                                     callback(error, '');
    //                                 }
    //                             });
    //                         } else {
    //                             let objv = new RawView(res);
    //                             objv.prepare({ status: 404, message: `ID DID not found on this DID!` });
    //                             objv.execute();
    //                         }
    //                     });
    //                 }
    //                 else {
    //                     let objv = new RawView(res);
    //                     objv.prepare({ status: 502, message: 'Campaign Registry Does not Match!' });
    //                     objv.execute()
    //                 }
    //             });
    //         }
    //         else {
    //             let objv = new RawView(res);
    //             objv.prepare({ status: 502, message: 'DID Not Available!' });
    //             objv.execute()
    //         }
    //     });
    // }
    /**
     * To Update entry with toll-free provisioning into Sinch :: 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 retrieve entry from Sinch :: first method
     */
    retrieveOsrEntry(req, res, callback) {
        let sdata = req.query;
        let did = sdata.DID;
        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);
                callback('', data);
            }
            else {
                callback(error, '');
            }
        });
    }
    /**
     * To Delete entry from Sinch :: 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;
        var headers = {
            'accept': '*/*',
            'Accept': 'application/json'
        };
        var options = {
            url: 'https://imported.numbers.api.sinch.com/v1beta1/projects/' + projectId + '/importedNumbers/' + number1,
            method: 'GET',
            headers: headers,
            auth: {
                'user': userId,
                'pass': passwd
            }
        };
        request(options, (error, response) => {
            if (!error) {
                let data = JSON.parse(response.body);
                if (data.status == 200) {
                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj.nonqrysql = "UPDATE `did_buy` SET `sinch_status`='0', `disconnect_did_status`='0' 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.SinchApi = SinchApi;
