// 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.1
 *
 * @module     : Downloader app
 * @author     : Alexander I. Chebykin <alex.chebykin@gmail.com>
 * @copyright  : Copyright (c) 2016-2017 Alexander I. Chebykin
 * @version    : 1.0
 * @build date : 2017-06-05
 * @license    : MIT
 * @link       : https://github.com/CAI79/CAI-CP
 ******************************************************************/

(function () {
    'use strict';

    /**
    * Return GET parameter from parent page
    *
    * @param  {string} key Key name
    * 
    * returns {string}
    */
    function $_PARENT_GET(key) {
//        var s = window.location.search;
        var s = (window.location !== window.parent.location)
                ? document.referrer
                : document.location.href;

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

        return s ? s[1] : false;
    }

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

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

        return s ? s[1] : false;
    }

    /**
     * Download system constructor
     *
     * @returns {undefined}
     */
    function DownloadSystem() {
        this.locales = 'en ru';
        this.lang = {};
    }

    /**
     * Download system initialization
     * 
     * @param   {string}   lang Language code. Ex: en, ru etc.
     * 
     * @returns {undefined}
     */
    DownloadSystem.prototype.init = function (lang) {
        var dl_instance = this,
            json_file = 'locale/',
            request = new XMLHttpRequest();

        if (this.check_locale(lang)) {
            json_file += lang + '.json';
        } else {
            json_file += 'en.json';
        }

        if (document.getElementById('lang') !== null) {
            document.getElementById('lang').value = lang;
        }

        if ($_GET('overwrite') && (document.getElementById('overwrite') !== null)) {
            document.getElementById('overwrite').checked = true;
        }

        request.open('GET', json_file);
        request.send();

        request.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    dl_instance.lang = JSON.parse(this.responseText);

                    document.getElementById('lbl_uri').textContent = dl_instance.lang.uri + ': ';
                    document.getElementById('lbl_dir').textContent = dl_instance.lang.dir + ': ';
                    document.getElementById('lbl_overwrite').textContent = dl_instance.lang.overwrite;
                    document.getElementById('lgn_log').textContent = dl_instance.lang.log;
                    document.getElementById('in_submit').value = dl_instance.lang.go;
                    document.getElementById('div_download').classList.toggle('hidden');
                    document.getElementById('div_log').classList.toggle('hidden');
                }
            }
        };
    };

    /**
     * Check locale support
     * 
     * @param   {string}  locale Locale code to check. Ex: en, ru etc.
     * 
     * @returns {Boolean}
     */
    DownloadSystem.prototype.check_locale = function (locale) {
        return this.locales.indexOf(locale.toLowerCase()) !== -1;
    };

    document.addEventListener('DOMContentLoaded', function () {
        /**
         * Initialize download object
         */
        var download = new DownloadSystem();

        if ($_GET('lang')) {
            download.init($_GET('lang'));
        } else if ($_PARENT_GET('lang')) {
            download.init($_PARENT_GET('lang'));
        } else {
            download.init('en');
        }

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

            xhr.onload = function () {
                var log_rec  = document.createElement('div'),
                    log_span = document.createElement('span'),
                    img_del  = document.createElement('img'),
                    hr       = document.createElement('hr');

                log_rec.classList.add('div_log_rec');
                log_rec.classList.add('hidden');

                img_del.classList.add('del_rec');
                img_del.src = '../../../gfx/buttons/delete.png';
                img_del.title = download.lang.del_log_rec;

                img_del.addEventListener('click', function () {
                    this.parentNode.parentNode.removeChild(this.parentNode);
                });

                log_rec.appendChild(log_span);
                log_rec.appendChild(img_del);
                log_rec.appendChild(hr);

//                document.getElementById('div_log_recs').appendChild(log_rec);
                document.getElementById('div_log_recs').insertBefore(log_rec,
                        document.getElementById('div_log_recs').childNodes[0]);

                if (xhr.responseText === '[langDownloadStarted]') {
                    msg = download.lang.download_started;
                } else {
                    msg = xhr.responseText;
                }

                log_span.appendChild(document.createTextNode(
                    cur_date.toLocaleString() + ': ' +
                        document.getElementById('dir').value + ' (' +
                        document.getElementById('uri').value + '): ' +
                        msg
                )
                    );

                log_rec.classList.toggle('hidden');
            };

            xhr.open(this.method, this.action, true);
            xhr.send(new FormData(this));

            return false;
        };
    });
}());
