var widget_version = null;
var appID = null;
var os = null;
var is_defined = false;
var file_del_count = 0;
var filecss_count = 0;
var site_path = 'http://127.0.0.1:8151/__internal__/';
var loader_version = null;

var set_array = [];
var set_counter = 0;
var is_reboot = false;

var is_logging = true;
var is_widget_loaded = false;
var load_timeout;
var widget_reload;

/*var sparam="199";
var curcode="";

var preload = function(){
	var stimer = setTimeout(()=>{
		init();
	}, 5000);
	document.addEventListener('keydown', function (event) {
		console.log("KEY: "+ e.key);
		if(!stimer) return;
		if(event.key === "Enter"){
			if(curcode === sparam){
			    if (localStorage.getItem("widget_version")) {
			    	localStorage.removeItem("widget_version");
			    	$("#info").html("Reload WIDGET.");
			    	setTimeout(()=>{
			    		window.location.reload();
			    	}, 3000);
			    }

			}
			else{
				if(stimer){
					clearTimeout(stimer);
					init();
				}
			}
		}
		curcode += event.key;
	});
}*/

var preload = function(){
	
    if (localStorage.getItem("debug_log") && localStorage.getItem("ip") && localStorage.getItem("room") || true) {
        const originalConsoleLog = console.log;
        console.log = function(...args) {
            //const message = args.join(' ');
            //   console.warn(`[Перехвачено] ${message}`);
            console_send(args);
            originalConsoleLog.apply(console, args);
        };
        const originalConsoleError = console.error;
        console.error = function(...args) {
            //const message = args.join(' ');
            //   console.warn(`[Перехвачено] ${message}`);
            console_send(args, true);
            originalConsoleError.apply(console, args);
        };
        const originalConsoleWarn = console.warn;
        console.warn = function(...args) {
            //const message = args.join(' ');
            //   console.warn(`[Перехвачено] ${message}`);
            console_send(args);
            originalConsoleWarn.apply(console, args);
        };
    }
    
    includesLib(function () {
                init();
            });
}

function includesLib(onload){
    if (!is_defined) {
        is_defined = true;
       if (typeof tizen !== "undefined") {
            os = 'Tizen';
            localStorage.setItem("os_version", os);
          //            $(document.head).append("<script type='text/javascript' src='$B2BAPIS/b2bapis/b2bapis.js'></script>");
            $(document.head).append("<script type='text/javascript' src='js/helper_tizen.js'></script>");
            console_log('Master Loader : Tizen OS detected');
            onload();
        } else {
            if (navigator.userAgent.indexOf("Android") >= 0) {
                os = 'Android';
                localStorage.setItem("os_version", os);
                document.body.style.zoom = 1 / window.devicePixelRatio;
                console_log('Master Loader : Android OS detected');
                onload();
            } else {
                os = 'WebOS';
                localStorage.setItem("os_version", os);
                //$(document.head).append("<script src='lib/idcap.js'></script>");
                //$(document.head).append("<script type='text/javascript' src='js/helper_webos.js'></script>");
                append_script('lib/idcap.js',
                        function () {
                            append_script('js/helper_webos.js',
                                function () {
	                                loader_version = localStorage.getItem("loader_version");
	                                console_log('Master Loader : Web OS detected');
	                                getXAITVersion();
	                                onload();
                              });
                        });


                //TODO
                //loader_version = null;

             }

        }

        
    }
}
function append_script(fileName, onload) {
    let node = document.createElement('script');
    node.src = fileName;
    node.onload = onload;
    node.defer = true;
    node.async = true;
    document.head.appendChild(node);
}

var init = function(to) {
    // TODO:: Do your initialization job
    //console.trace();
    //  if (!localStorage.getItem("MasterConsoleLog")) {
	
    localStorage.setItem("MasterConsoleLog", "[]");

    //}
    console_log('Master loader called to=' + (to ? JSON.stringify(to) : ''));
    console_log('Master loader version: ' + getLoaderVersion());

    window.addEventListener("error", (e) => {
        let err = (new Date()).toString() + JSON.stringify(e, ["message", "arguments", "type", "name"]) +
            ' Filename:' + e.filename +
            ' Line Number:' + e.lineno +
            ' Column Number:' + e.colno +
            ((e.error && e.error.stack) ? (' Stack Trace:' + e.error.stack) : '');
        console_log(err);
        setTimeout(function() {

            location.reload();
        }, 30000);

    });

    if (to && typeof to === 'number' && to !== 0) {
        window.setTimeout(function() {
            console_log('Master loader recalled after ' + to);
            location.reload();
        }, to);
        return;

    }
    let wv = localStorage.getItem("widget_version");
    if (wv) {
        if (wv !== "0.0.0") {
            const queryString = window.location.search;
            if (queryString) {
                const urlParams = new URLSearchParams(queryString);
                widget_reload = urlParams.get('param');
                if (widget_reload) {
                    console_log('Master loader clear widget_version');
                    localStorage.removeItem("widget_version");
                    widget_version = null;
                }
            }
        } else {
            localStorage.removeItem("widget_version");
        }
    }


    if (localStorage.getItem("widget_version")) {
        widget_version = localStorage.getItem("widget_version");

        //TODO
        //widget_version = null;
    }

    console_log("Master Loader widget_version: " + widget_version);

    beforeRun(function(e) {

        console_log('Master Loader: BeforeRun completed : is_reboot = ' + is_reboot);
        if (is_reboot) {
            rebootDevice();
            return;
        }

        if (widget_version) {
            ReadMainPage(function(e) {
                console_log("Master Loader : Find load widget: href=" + e);
                window.location.href = e;
            }, function(e) {
                console_log("Master Loader : Find Widget error: load page not found, reload ");
                localStorage.removeItem("widget_version");
                widget_version = null;
                init(1000);
            });
            return;
        }

        CheckWidget(
            function(e) {

                if (e === 404) {
                    console_log("Master Loader : CheckWidget error request: server api not found, continue");
                    //                init(60000);
                    //                return;
                }
                if (!widget_version) {
                    console_log("Master Loader : CheckWidget error request: widget version not load. Wait 30 sec.");
                    init(30000);
                    return;
                }
                ReadMainPage(function(e) {
                    console_log("Master Loader : CheckWidget load: " + e);
                    window.location.href = e;
                }, function(e) {
                    console_log("Master Loader : CheckWidget error: load page not found ");
                    //                    localStorage.removeItem("widget_version");
                    widget_version = null;
                    init(10000);
                });

            },
            function(e) {
                console_log("Master Loader : CheckWidget error load: " + e);
                init(60000);
                return;
            }
        );
    });



};

function console_log(msg, style) {
    //	console.trace();
    if (style) console.log('%c' + msg, style);
    else console.log(msg);
    let d = new Date,
        dformat = [d.getDate(),
            d.getMonth() + 1,
            d.getFullYear()
        ].join('/') + ' ' + [d.getHours(),
            d.getMinutes(),
            d.getSeconds()
        ].join(':');
    if (typeof is_logging !== 'undefined')
        addToStorage(dformat + "-" + msg);

    if (document.getElementById('test'))
        document.getElementById('test').innerHTML += dformat + "-" + msg + "<br/>";

}

function addToStorage(str) {
    var arr = JSON.parse(localStorage.getItem("MasterConsoleLog"));
    if (!Array.isArray(arr)) arr = [];

    arr.push(str);

    localStorage.setItem("MasterConsoleLog", JSON.stringify(arr));
}


function CheckWidget(onleave, onerror) {

    console_log("Master Loader: Check Widget");

    //    if (widget_version && !localStorage.getItem("widget_files")) {
    //        console.log("widget_files not found, reset widget version.");
    //        widget_version = null;
    //    }

    var ub = getServerUrl();
    url = ub + "api/command/CheckWidget?ver=" + widget_version;


    //        alert(url);
    console_log("Master Loader Send Check Widget URL: " + url);
    var is_lock_error = false;

    var client = new XMLHttpRequest();
    client.open('GET', url);
    client.timeout = 5000;
    client.onreadystatechange = function(e) {
        if (client.readyState === 4 && client.status === 200) {
            var resp = client.responseText;
            console_log("Master Loader CheckWidget key sended " + resp);

            if (resp.length > 0 && resp !== '""') {
                let docs = JSON.parse(resp);
                if (!docs.Result) {
                    onerror("Error responce: " + resp);
                    return;
                }

                if (os === 'Tizen' || os === 'Android') {
                    localStorage.setItem("widget_files", JSON.stringify(docs.Result));
                    if (localStorage.getItem("portal")) {
                        localStorage.removeItem("portal");
                    }
                } else {
                    setWidgetFiles(JSON.stringify(docs.Result));
                }



                var widget_version_load = docs.Version;
                if (widget_version && widget_version === widget_version_load) {
                    console_log("Master Loader CheckWidget: Find Widget " + widget_version + " Load ver. " + widget_version_load + " no load required");
                    onleave();
                    return;
                }

                console_log("Master Loader CheckWidget: Load Widget required " + widget_version_load);
                if (widget_version)
                    localStorage.removeItem("widget_version");

                load_timeout = setTimeout(() => onerror('Master Loader: LoadWidget Timeout error'), 180000);

                LoadWidget(docs.Result,
                    function(dir) {
                        if (load_timeout) clearTimeout(load_timeout);

                        localStorage.setItem("widget_version", widget_version_load);
                        console_log('Master Loader Downloads widget completed ' + widget_version_load);
                        widget_version = widget_version_load;
                        localStorage.setItem("loader_version", getLoaderVersion());
                        is_widget_loaded = true;
                        onleave();
                    },
                    function(e) {
                        if (load_timeout) clearTimeout(load_timeout);
                        console_log("Master Loader Error " + JSON.stringify(e));
                        onerror("Document Load Error " + JSON.stringify(e));
                    }
                );

                return;
            } else {
                console_log('Master Loader : no update required');
                onleave();
                return;
            }

        }
        if (client.readyState == 4 && client.status !== 200) {

            console_log('Master Loader : error 500 status = ' + client.status + " e = " + JSON.stringify(e));
            if (!is_lock_error) {
                is_lock_error = true;
                onleave(500);
            }
        }


    };

    client.onload = function() {

        //    	document.getElementById('test').innerHTML += "Master Loader : onload status "+client.status+"<br/>";
        if (client.status === 404) {
            onleave(404);
        }
        return;
    }

    client.onerror = function(e) {

        console_log('Master Loader : error request: ' + JSON.stringify(e));
        if (!is_lock_error) {
            onleave();
        }
        return;
    }
    client.ontimeout = client.onerror;

    client.send(); /* Send to server */
}



function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

function console_send(args, is_err) {

    let d = new Date,
        dformat = [d.getDate(),
            d.getMonth() + 1,
            d.getFullYear()
        ].join('/') + ' ' + [d.getHours(),
            d.getMinutes(),
            d.getSeconds()
        ].join(':');

    let servl = getServerUrl() + "api/command/SendClientLog";
    let app_id = localStorage.getItem("room");
    let msg;
    let style = "";
    if (is_err) {
        style = "color: red;";
        msg = args.join(' ');
    } else {
        if (Array.isArray(args)) {

            if (args.length > 1 && args[0].startsWith('%c')) {
                style = args[1];
                msg = args[0].replace('%c', '');
            } else {
                msg = args.join(' ');
            }
        } else {
            msg = args.toString();
        }

    }

    $.ajax({
        type: 'POST',
        url: servl,
        data: {
            id: app_id,
            text: dformat + " - " + msg,
            style: style,
            ip: localStorage.getItem("ip")
        }
    });
}

window.onload = preload;