// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.

//let httpUrl = 'http://127.0.0.1:6688';
//let mqttUrl = 'ws://localhost:8384/mqtt';
//let basicUrl = 'http://localhost:8384';
var href = window.location.href;
var path = window.location.pathname;
let basicUrl = href.slice(0, href.indexOf(path));
let httpUrl = basicUrl.slice(0, basicUrl.length-4) + "6688";

let mqttUrl = "ws:" + basicUrl.slice(basicUrl.indexOf("//")) + "/mqtt";

let url = '/Config/';
let containerDiv = 'configcontainer';
let contentDiv = 'content';
let defaultFnav = 'FuelConfigFnav';
let defaultPageDic = new Array();
defaultPageDic['FuelConfigFnav'] = 'PriceChangeRnav';
defaultPageDic['TankConfigFnav'] = 'ProbeConfigRnav';
defaultPageDic['FairbanksFnav'] = 'FairbanksRnav';

let options = {
    clientId: 'mqttjs_' + (Math.random() * 1000000).toString(),
    timeout: 5000,
    useSSL: false
};
let client = mqtt.connect(mqttUrl, options);

client.on('connect',
    function (res) {
        console.log(res);
        client.subscribe('/sys/atg_classic_App/Application.ATG_Classic_App.App/thing/service/GetConfigAsync_reply',
            function (err) {
                if (err) {
                    console.log(err);
                }
            });
        client.subscribe('/sys/atg_classic_App/Application.ATG_Classic_App.App/thing/service/UpsertConfigAsync_reply',
            function (err) {
                if (err) {
                    console.log(err);
                }
            });
        client.subscribe('/sys/fairbanksRealTimeDataApp/Dfs.WayneChina.FairbanksRTData.FairbanksRealTimeDataApp/thing/service/GetAppConfigAsync_reply',
            function (err) {
                if (err) {
                    console.log(err);
                }
            });
        client.subscribe('/sys/fairbanksRealTimeDataApp/Dfs.WayneChina.FairbanksRTData.FairbanksRealTimeDataApp/thing/service/PutConfigAsync_reply',
            function (err) {
                if (err) {
                    console.log(err);
                }
            });
        client.subscribe('/sys/Vapor_Recovery_App/Application.VaporRecoveryApp.App/thing/service/GetConfigAsync_reply',
            function (err) {
                if (err) {
                    console.log(err);
                }
            });
        client.subscribe('/sys/Vapor_Recovery_App/Application.VaporRecoveryApp.App/thing/service/PutConfigAsync_reply',
            function (err) {
                if (err) {
                    console.log(err);
                }
            });
    });

client.on('error',
    function (err) {
        console.log(err);
        client.end();
    });

client.on('message',
    function (topic, message) {
        //console.log(topic, message.toString());
        OnReply(JSON.parse(message.toString()));
    });

function Publish1(path) {
    client.publish(path, '[]');
}

function Publish(name, value, path) {
    let parameters = '{"Parameters": [{"Name": "';
    parameters += name;

    parameters += '", "Value": "';
    parameters += value.replace(new RegExp('"', 'gm'), '\\"') + '"}]}';

    console.log(parameters);
    client.publish(path, parameters);
}

function OnloadConfig() {
    RenderDiv(url + defaultFnav, containerDiv, url + defaultPageDic[defaultFnav], contentDiv);
}

function RenderDiv(containerUrl, containerDiv, contentUrl, contentDiv) {
    $.ajax({
        url: containerUrl,
        success: function (result) {
            $('#' + containerDiv).html(result);
            if (contentUrl) {
                RenderDiv(contentUrl, contentDiv, null, null);
            }
        },
        error: function (msg) {
            console.log(msg);
        }
    })
}

function RenderContainer(currentId, fnav) {
    RenderDiv(url + currentId, containerDiv, url + defaultPageDic[currentId], contentDiv);
    ToggleClass(currentId, fnav);
}

function RenderContent(currentId, rnav) {
    RenderDiv(url + currentId, contentDiv, null, null);
    ToggleClass(currentId, rnav);
}

function OnChangeLanguage(locale, array) {
    for (let i = 0; i < array.length; i++) {
        if ('en-US' === locale) {
            array[i].style.fontSize = '1.1rem'
        } else {
            array[i].style.fontSize = ''
        }
    }
}

function ToggleClass(currentId, array) {
    for (let i = 0; i < array.length; i++) {
        let classNames = array[i].className;
        let classImage = classNames.split(' ')[0] + '-image';
        let id = array[i].id;

        if (classNames.length > 1) {
            $('#' + id).removeClass(classImage);
        }
        if (currentId == id) {
            $('#' + id).addClass(classImage);
        }
    }
}

function InvokeHttpGet(apiUrl, callback) {
    $.ajax({
        url: httpUrl + apiUrl,
        contentType: 'application/json',
        success: function (res) {
            callback(res);
        },
        error: function (msg) {
            console.log(msg)
        }
    })
}

function InvokeHttpPost(apiUrl, reqdata, callback) {
    $.ajax({
        url: httpUrl + apiUrl,
        contentType: 'application/json',
        data: JSON.stringify(reqdata),
        type: 'post',
        success: function (res) {
            callback(res);
        },
        error: function (msg) {
            console.log(msg);
        }
    })
}

var apis = new Map();
function ShowMeAPIS(parameter,callBack) {
    var serviceUrl = basicUrl +"/u/?apitype=service&an=ShowMeApi&pn=ProcessorsDispatcher&en=Edge.Core.Processor.Dispatcher.DefaultDispatcher";
    $.ajax({
        url: serviceUrl,
        datatype: "application/json",
        type: 'post',
        contentType: "application/json;charset=utf-8;",
        data: JSON.stringify(parameter),
        beforeSend: function () {
        },
        success: function (data) {
            console.log(data);
            data.forEach(function (d) {
                if (d.Path === null) return;
                if (apis.has(d.ApiName)) {
                    apis.delete(d.ApiName);
                }
                apis.set(d.ApiName, d.Path.slice(d.Path.length - 1) === "+" ? d.Path.slice(0, d.Path.length - 1) : d.Path);
            });
            // subscribeEvents();
            if (callBack !== null) callBack();
        },
        error: function (err) {
            console.log(err);
            if (callBack !== null) callBack();
        }
    });
}
function GetDataByAPIS(apiName, parameter,method,callBack) {
    if (apis.size === 0 || !apis.has(apiName)) return;
    $.ajax({
        url: basicUrl+apis.get(apiName),
        datatype: "application/json",
        type: method,
        contentType: "application/json;charset=utf-8;",
        data: JSON.stringify(parameter),
        beforeSend: function () {
        },
        success: function (data) {
            console.log(data);
            if (callBack !== null) callBack(data);
        },
        error: function (err) {
            console.log(err);
            if (callBack !== null) callBack(err);
        }
    });
}