/**
 * Created by Gifer on 04.05.2017.
 */
"use strict";

var localPath  =  isIE()
    ? window.location.protocol + "//" + window.location.host
    : window.location.origin;
var components = {};
var options    = {};
var currentOS  = 'win';
var LangSource = {};
var hexCodes   = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
var Base64     = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
                this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }

            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else
            if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i  = 0;
        var c  = 0;
        var c1 = 0;
        var c2 = 0;
        var c3 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else
            if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
};
var localizeParams = {};
var Hash       = "";

// ===================================================
// ===================================================

function SHA1() {
    var sha1 = new Rusha();
    sha1.resetState();

    return sha1;
}

function copy (Src, From, Count){
    return (Src) ? Src.slice(From, From + (Count || (Src.length - From))) : "";
}

function getSearchQuery(src, condition, simple) {
    var data = null;

    src = copy(src, 1).split('&');

    for (var i = 0; i < src.length; i++){
        if (src[i].indexOf(condition + "=") === 0){
            if (simple) {
                data = decodeURI(src[i].split('=')[1]);

                break;
            } else {
                if (!data){
                    data = [];
                }

                data.push(src[i]);
            }
        }
    }

    return data;
}

function toHex(number, length){
    var str = "";

    number = parseInt(number,10);

    while (number > 0){
        str    = hexCodes[number%16] + str;
        number = Math.floor(number / 16);
    }

    while (str.length < length){
        str = "0" + str;
    }

    return str;
}

function makeCRCTable(){
    var c;
    var crcTable = [];

    for(var n =0; n < 256; n++){
        c = n;

        for(var k =0; k < 8; k++){
            c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
        }

        crcTable[n] = c;
    }

    return crcTable;
}

function CRC32(str) {
    var crcTable = makeCRCTable();
    var crc = 0 ^ (-1);

    for (var i = 0; i < str.length; i++ ) {
        crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
    }

    return (crc ^ (-1)) >>> 0;
}

function isIE(){
    //return '\v'=='v';

    var tmp = document.documentMode, _isIE;

    // Try to force this property to be a string.
    try {
        document.documentMode = "";
    } catch(e){ }

    // If document.documentMode is a number, then it is a read-only property, and so
    // we have IE 8+.
    // Otherwise, if conditional compilation works, then we have IE < 11.
    // Otherwise, we have a non-IE browser.
    _isIE = typeof document.documentMode === "number" || eval("/*@cc_on!@*/!1");

    // Switch back the value to be unobtrusive for non-IE browsers.
    try{document.documentMode = tmp;}
    catch(e){ }

    return _isIE;
}

function $$(item, all) {
    var res = null;

    if (item[0] === '.'){
        res = all ? document.getElementsByClassName(item.replace(".", "")) : document.getElementsByClassName(item.replace(".", ""))[0];
    } else
    if (item[0] === '#'){
        res = document.getElementById(item.replace("#", ""));
    }

    return res;
}

function showView(view){
    view.style.display = 'block';
}

function hideView(view){
    view.style.display = 'none';
}

function setDownloadLink(pwd){
    var source = window.location.hostname + "|" +
        options.MCPort + "|" +
        options.ServerName + "|" +
        (options.UseServerPass ? pwd : "")
    ;

    var calcB64 = Base64.encode(
        toHex(CRC32(Base64._utf8_encode(source)), 2) + "|" +
        source
    );

    components.win32Link.setAttribute("href",
        localPath +
        "/setup/mcclient_" +
        calcB64 + (calcB64[calcB64.length - 1] !== "=" ? "=" : "") + // проверяем посчитанный base64, если вконце нету "=", то добавляем "=", иначе приозодет взыв ...
        ".exe"
    );
}

function parseData(_data) {
    options = JSON.parse(_data);

    components.CompanyName.innerHTML = '"' + options.ServerName + '"';

    handlingActions();

    if (options.UseServerPass){
        showView(components.firstStep_win);

        if (components.win32Link.className.indexOf("disable") === -1) {
            components.win32Link.className += " disable";
        }
    } else {
        hideView(components.firstStep_win);

        setDownloadLink();
    }

    localizeParams.mcInstallMACOS_step4   = [window.location.hostname, options.MCPort];
    localizeParams.mcInstallLinux_step4   = [window.location.hostname, options.MCPort];
    localizeParams.mcInstallAndroid_step3 = [window.location.hostname, options.MCPort];

    components.chatLnk  .href = "/" + options.Aliases.chat.path;
    components.adminLnk .href = "/" + options.Aliases.admin.path;
    components.kanbanLnk.href = "/" + options.Aliases.kanban.path;
    components.forumLnk .href = "/" + options.Aliases.forum.path;

    loadLangs(detectLang());
}   

function init() {
    var changeLang = $$('.changeLang', true);

    components.CompanyName   = $$("#CompanyName");
    components.clientTypes   = $$(".clientVariants", true);
    components.servPwd       = $$("#servPwd");
    components.win32Link     = $$("#win32Link");
    components.firstStep_win = $$("#firstStep_win");
    components.enterServPwd  = $$("#enterServPwd");

    components.chatLnk       = $$("#chatLnk");
    components.adminLnk      = $$("#adminLnk");
    components.kanbanLnk     = $$("#kanbanLnk");
    components.forumLnk      = $$("#forumLnk");

    for(var itm = 0; itm < changeLang.length; itm++){
        changeLang[itm].addEventListener('click', function () {
            loadLangs(this.getAttribute("lang"));
        });
    }

    function disableBtn(){
        components.win32Link.setAttribute("href", "");

        if (components.win32Link.className.indexOf("disable") === -1) {
            components.win32Link.className += " disable";
        }

    }

    function check(){
        var calcSha1   = SHA1();

        if (components.servPwd.value){
            calcSha1.append(components.servPwd.value);
            Hash = calcSha1.end();

            if (Hash === options.ServPass){
                setDownloadLink(components.servPwd.value);

                components.win32Link.className = components.win32Link.className.replace(" disable", "");
            } else {
                disableBtn();
            }
        } else {
            disableBtn();
        }

        components.enterServPwd.style.display = "none";
    }

    components.win32Link.addEventListener('click', function (e){
        if (options.UseServerPass && Hash !== options.ServPass) {
            components.enterServPwd.style.display = "block";
            e.preventDefault();

            setTimeout(function () {
                components.servPwd.focus();
            }, 20);
        }
    });
    
    components.servPwd.addEventListener('keyup', check);
    components.servPwd.addEventListener('change', check);

    // if (lang) {
    //     loadLangs(lang);
    // }
}

function getCompanyData(cb) {
    var req = new XMLHttpRequest();

    req.open('POST', localPath + "/rest/_lobbyGetServerName_", true);
    req.send(null);

    req.onreadystatechange = function(){
        if(this.readyState === this.DONE) {
            cb(this.responseText);
        }
    };
}

function getQrCode(cb) {
    var req = new XMLHttpRequest();

    req.open('POST', localPath + "/rest/_androidQrCode_", true);
    req.send(location.hostname);

    req.onreadystatechange = function(){
        if(this.readyState === this.DONE) {
            cb(this.responseText);
        }
    };
}

function handlingActions() {
    for (var btn = 0; btn < components.clientTypes.length; btn++){
        components.clientTypes[btn].addEventListener('click', function () {
            if (this.tagName === "BUTTON") {
                hideView($$("#" + currentOS));

                currentOS = this.getAttribute('os');

                var prevBtn = $$('.btn-primary');
                prevBtn.className = prevBtn.className.replace(' btn-primary shadow', "");

                this.className += ' btn-primary shadow';

                showView($$("#" + currentOS));

                var os = this.getAttribute("os");

                if (os === "android" || os === "ios"){
                    document.getElementById("__qr_code__" + os).innerHTML = "";
                    
                    getQrCode(function (code){
                        new QRCode(document.getElementById("__qr_code__" + os), {
                            text         : "https://mychat-server.com:50000/?id=" + options.ServerID + "&o=" + code,
                            width        : 250,
                            height       : 250,
                            colorDark    : "#131313",
                            colorLight   : "#ffffff",
                            correctLevel : QRCode.CorrectLevel.H
                        });
                    })
                }
            }
        });
    }
}

function detectLang(){
    var lang = getSearchQuery(window.location.search, "lang",  true) || (window.navigator.language || window.navigator.userLanguage).slice(0, 2).toLowerCase();

    if (lang !== 'en' && lang !== 'ru' && lang !== 'uk'){
        lang = 'en';
    }

    return lang;
}

function myReplace(source, items, term){
    var res = source;

    if (items !== undefined && source !== undefined){
        var _term = term || "%s";

        if (items.length > 0){
            res = source.toString().replace(_term, items.shift());
            res = myReplace(res, items, _term);
        }
    }

    return res;
}

function localize(source) {
    var itm;
    var links = source.links;

    delete source.links;
    
    for (var name in source){
        itm = $$("#" + name);

        if (itm){
            itm.innerHTML = source[name];

            if (localizeParams.hasOwnProperty(name)){
                itm.innerHTML = myReplace(itm.innerHTML, [].concat(localizeParams[name]));
            }
        }
    }

    for (var link in links){
        itm = $$("#" + link);

        if (itm){
            itm.href = links[link];
        }
    }
}

function loadLangs(lang) {
    var req = new XMLHttpRequest();

    req.open('GET', localPath + "/textsource/www/lobby/" + lang + ".json", true);
    req.send(null);

    req.onreadystatechange = function(){
        if(this.readyState === this.DONE) {
            if (this.status === 200) {
                LangSource = JSON.parse(this.responseText);

                localize(LangSource);

                $$("#appleLink").href = lang === 'en'
                    ? "https://apps.apple.com/us/app/mychat-client/id1560836210?ign-itscg=30200&ign-itsct=apps_box_badge#?platform=iphone"
                    : "https://apps.apple.com/ru/app/mychat-client/id1560836210?ign-itscg=30200&amp;ign-itsct=apps_box_badge#?platform=iphone";

                $$('#playMarketImg').src = "https://play.google.com/intl/en_us/badges/images/generic/" + (lang === 'uk' ? 'ua' : lang) + "_badge_web_generic.png"
            }
        }
    };
}

// ===================================================
// ===================================================

init();

getCompanyData(parseData);
