// MIT License:
//
// Copyright (c) 2016-2017, Alexander I. Chebykin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 * CAI CP v.0.9
 *
 * @module     : Configuration subsystem
 * @author     : Alexander I. Chebykin <alex.chebykin@gmail.com>
 * @copyright  : Copyright (c) 2016-2017 Alexander I. Chebykin
 * @version    : 0.9
 * @build date : 2017-07-23
 * @license    : MIT
 * @link       : https://github.com/CAI79/CAI-CP
 ******************************************************************/

(function () {
    'use strict';

    /**
    * Return GET parameter
    *
    * @param  {string} key Key name
    * 
    * returns {string}
    */
    function $_GET(key) {
        var s = window.location.search;

        s = s.match(new RegExp(key + '=([^&=]+)'));

        return s ? s[1] : false;
    }

    /**
     * SetupSystem constructor
     *
     * @returns {undefined}
     */
    function SetupSystem() {
        this.locale = 'en';
        this.langs  = [];
        this.tranlation = [];
    }

    /**
     * 
     * @param   {int}      init_level Initialization level: 1 - configure language
     *                                                      2 - do localization
     *                                                      3 - load languages list
     * 
     * @returns {undefined}
     */
    SetupSystem.prototype.init = function (init_level) {
        var setup_instance = this,
            request = new XMLHttpRequest(),
            res_data;

        switch (init_level) {
        case 1: // Configure language
            if ($_GET('lang') !== '') {
                this.locale = $_GET('lang');
            } else {
                request.open('GET', '../../../json/settings.json');
                request.send();

                request.onreadystatechange = function () {
                    if (this.readyState === 4) {
                        if (this.status === 200) {
                            res_data = JSON.parse(this.responseText);
                            setup_instance.locale = res_data.lang;
                        }
                    }
                };
            }
            this.init(2);
            break;
        case 2: // Do localization
            request.open('GET', '../../../json/locale/' + this.locale + '.json');
            request.send();

            request.onreadystatechange = function () {
                if (this.readyState === 4) {
                    if (this.status === 200) {
                        res_data = JSON.parse(this.responseText);
                        setup_instance.tranlation = res_data;

                        document.getElementById('lbl_dim_on_create').textContent = res_data.dim_on_create;
                        document.getElementById('lbl_default_language').textContent = res_data.default_language;
                        document.getElementById('lbl_check_files_rights').textContent = res_data.check_files_rights;
                        document.getElementById('lbl_check_hdd_temp_interval').textContent = res_data.check_hdd_temp_int;
                        document.getElementById('lbl_check_users_online_interval').textContent = res_data.check_users_online_int;
                        document.getElementById('lbl_max_hdd_temp').textContent = res_data.max_hdd_temp;
                        document.getElementById('lbl_check_smart_interval').textContent = res_data.check_smart_int;
                        document.getElementById('lbl_temp_secs').textContent = res_data.secs;
                        document.getElementById('lbl_smart_secs').textContent = res_data.secs;
                        document.getElementById('lbl_users_online_secs').textContent = res_data.secs;
                        document.getElementById('fsl_general').textContent = res_data.general_settings;
                        document.getElementById('fsl_monitoring').textContent = res_data.monitoring;
                        document.getElementById('fsl_apps').textContent = res_data.applications;
                        document.getElementById('lbl_enabled').textContent = res_data.enbld;
                        document.getElementById('lbl_app_name').textContent = res_data.application;
                        document.getElementById('lbl_app_ver').textContent = res_data.version;
                        document.getElementById('lbl_app_author').textContent = res_data.author;
                        document.getElementById('in_submit').value = res_data.save;

                        document.getElementById("frm_submit").classList.remove('hidden');
                    }
                }
            };
            this.init(3);
            break;
        case 3: // Load languages list
            request.open('GET', '../../../json/settings.json');
            request.send();

            request.onreadystatechange = function () {
                if (this.readyState === 4) {
                    if (this.status === 200) {
                        var select_lang = document.getElementById('default_language');

                        res_data = JSON.parse(this.responseText);

                        document.getElementById('dim_on_create').checked = res_data.dim_on_create;
                        document.getElementById('chk_files_rights').checked = res_data.check_files_rights;
                        document.getElementById('chk_temp_interval').value = res_data.check_hdd_temp_interval;
                        document.getElementById('chk_smart_interval').value = res_data.check_smart_interval;
                        document.getElementById('chk_users_online_interval').value = res_data.check_users_online_interval;
                        document.getElementById('max_hdd_temp').value = res_data.max_hdd_temp;

                        setup_instance.langs = res_data.langs;

                        for (var language in res_data.langs) {
                            var opt_lang = document.createElement('option');

                            opt_lang.value = language;
                            opt_lang.appendChild(document.createTextNode(res_data.langs[language]));

                            if (res_data.lang === language) {
                                opt_lang.selected = true;
                            } else if (!$_GET('lang') && setup_instance.locale === language){
                                opt_lang.selected = true;
                            }

                            select_lang.appendChild(opt_lang);
                        }
                    }
                }
            };
            this.init(4);
            break;
        case 4: // Load apps list
            request.open('GET', '../../../apps/?do=get_apps');
            request.send();

            request.onreadystatechange = function () {
                if (this.readyState === 4) {
                    if (this.status === 200) {
                        var apps_table = document.getElementById('tbl_apps'),
                            apps_tr,
                            apps_td,
                            apps_name,
                            apps_caption,
                            apps_check,
                            i = 0;
                        res_data = JSON.parse(this.responseText);
                        for (var app_info in res_data) {
                            apps_tr = document.createElement('tr');
                            apps_td = document.createElement('td');

                            apps_caption = document.createElement('input');
                            apps_caption.type  = 'hidden';
                            apps_caption.name  = 'app_caption[' + i + ']';
                            apps_caption.value = res_data[app_info].caption;
                            apps_td.appendChild(apps_caption);

                            apps_name = document.createElement('input');
                            apps_name.type  = 'hidden';
                            apps_name.name  = 'app_name[' + i + ']';
                            apps_name.value = app_info;
                            apps_td.appendChild(apps_name);

                            apps_check = document.createElement('input');
                            apps_check.type    = 'checkbox';
                            apps_check.name    = 'app_enabled[' + i + ']';
                            apps_check.value   = '1';
                            apps_check.checked = res_data[app_info].enabled;

                            apps_td.appendChild(apps_check);
                            apps_tr.appendChild(apps_td);
                            apps_td = document.createElement('td');
                            apps_td.appendChild(document.createTextNode(res_data[app_info].caption));
                            apps_tr.appendChild(apps_td);
                            apps_td = document.createElement('td');
                            apps_td.appendChild(document.createTextNode(res_data[app_info].version));
                            apps_tr.appendChild(apps_td);
                            apps_td = document.createElement('td');
                            apps_td.appendChild(document.createTextNode(res_data[app_info].author));
                            apps_tr.appendChild(apps_td);
                            apps_table.appendChild(apps_tr);
                            i++;
                        }
                    }
                }
            };
        }
    };

    document.addEventListener('DOMContentLoaded', function () {
        'use strict';

        /**
         * Initialize setup object
         */
        var setup = new SetupSystem();

        setup.init(1);

        document.getElementById('frm_submit').onsubmit = function () {
            var xhr = new XMLHttpRequest();

            xhr.onload = function () {
                if (xhr.responseText === 'true') {
                    alert(setup.tranlation.settings_saved);
                    window.top.location.reload(true);
                } else {
                    alert(setup.tranlation.error);
                }
            };

            if (this.method.toLowerCase() === 'post') {
                xhr.open (this.method, this.action, true);
                xhr.send (new FormData (this));
            } else {
                var element,
                    el_type,
                    file,
                    search = '';
                for (var i = 0; i < this.elements.length; i++) {
                    element = this.elements[i];
                    if (!element.hasAttribute('name')) { continue; }
                    el_type = element.nodeName.toLowerCase() === 'input' ?
                        element.getAttribute('type').toLowerCase() : 'text';
                    if (el_type === 'file') {
                        for (file = 0; file < element.files.length;
                            search += '&' + escape(element.name) + '=' + escape(element.files[file++].name));
                    } else if ((el_type !== 'radio' && el_type !== 'checkbox') || element.checked) {
                        search += '&' + escape(element.name) + '=' + escape(element.value);
                    }
                }
                xhr.open('get', this.action.replace(/(?:\?.*)?$/, search.replace(/^&/, '?')), true);
                xhr.send(null);
            }

            return false;
        };

    });

}());
