var HL = HL || {};

HL.upload = (function() {
    var container = OU.utils.createElement('div'),
        data = {
            imported: null,
            exported: null
        },
        textarea = document.createElement('textarea'),
        input;

    var init = function() {
        initButtons();
        initTextarea();
    };

    var initTextarea = function() {
        container.appendChild(textarea);
    };

    var initButtons = function() {
        var label;

        input = document.createElement('input');
        input.type = 'file';
        input.id = 'upload-file';
        input.className = 'screen-reader';
        input.addEventListener('change', importData);

        label = document.createElement('label');
        label.textContent = 'Import';
        label.className = 'btn osep';
        label.setAttribute('for', input.id);

        container.appendChild(input);
        container.appendChild(label);
        container.appendChild(OU.buttons.create({
            type: 'export',
            html: 'Export',
            classes: ['osep'],
            click: exportData
        }));

        input = document.createElement('input');
        input.type = 'text';
        input.value = 'data';

        label = document.createElement('label');
        label.textContent = 'Filename: ';
        label.className = 'filename-input';
        label.appendChild(input);
        label.insertAdjacentHTML('beforeEnd', '.json');
        container.appendChild(label);
    };

    var importData = function(e) {
        var files = e.target.files,
            reader = new FileReader();

        reader.onload = (function() {
            return function(e) {
                if (files[0].name.indexOf('.json') < 0) {
                    input.value = 'Invalid file';
                    return;
                }

                data.imported = JSON.parse(e.target.result);
                textarea.textContent = JSON.stringify(data.imported, null, 4);
                input.value = files[0].name.replace('.json', '');
            };
        })(files[0]);

        reader.readAsText(files[0]);
    };

    var exportData = function() {
        var file = new Blob([JSON.stringify(data.exported)], {encoding:"UTF-8", type: "text/plain;charset=utf-8"});
        saveAs(file, (input.value || 'data') + '.json');
    };

    return {
        container: container,
        textarea: textarea,
        init: init,
        data: data
    };
})();