let fileObject = null;
window.onAddFile = function(object)
{
    fileObject = object;
    $('input[name="source"]').prop('checked', false);
    $('.file-selector-btn').addClass('hidden');
    loadLocalTables();
}

window.onRemoveFile = function()
{
    fileObject = null;
    $('.select-table').addClass('hidden');
    $('.file-selector-btn').removeClass('hidden');
}

window.onSelectFile = function(fileList)
{
    const fileTypeLang = $('.create-form').data('fileTypeLang');
    const isXlsx = fileList[0].name.endsWith('.xlsx');
    if(!isXlsx) return zui.Modal.alert({message: fileTypeLang});
}

function loadLocalTables()
{
    const file = fileObject.file;
    if(!file) return;

    let $picker = $('.select-table .picker-box').zui('picker');
    let reader  = new FileReader();
    $.getLib(config.webRoot + 'js/sheetjs/xlsx.full.min.js', {root: false}, function()
    {
        reader.onload = function(ev)
        {
            const tables   = [];
            const data     = ev.target.result;
            const workbook = XLSX.read(data);
            for(let index in workbook.SheetNames)
            {
                const sheetName = workbook.SheetNames[index];
                if(sheetName == 'CB_DATA_') continue;
                tables.push({text: sheetName, value: index});
            }

            $('.select-table').removeClass('hidden');
            $picker.$.setValue('');
            $picker.render({items: tables});
        };
        reader.readAsArrayBuffer(file);
    });
    
}

function loadRemoteTables()
{
    let $picker = $('.select-table .picker-box').zui('picker');
    $picker.render({items: []});
    $picker.$.setValue('');
    const sourceID = $('input[name="source"]:checked').closest('.history-item').data('sourceID');
    const link     = $.createLink('perfdatasource', 'ajaxGetTables', `sourceID=${sourceID}&isHtml=0`);
    $.get(link, function(data)
    {
        if(data)
        {
            const res    = JSON.parse(data);
            const tables = [];
            res.data.forEach((item, index) => {
                tables.push({value: index, text: item});
            });
            $('.select-table').removeClass('hidden');
            $picker.render({items: tables});
        }
    });
}

window.changeSource = function()
{
    const notesLang = $('.create-form').data('notesLang');
    const $file     = $('.form-group .file-selector').zui('fileSelector').$;
    if(fileObject)
    {
        zui.Modal.confirm({message: notesLang.upload, icon:'icon-exclamation-sign', iconClass: 'warning-pale rounded-full icon-2x'}).then((res) =>
        {
            if(res)
            {
                $file.removeFile(fileObject.id, fileObject.name);
                loadRemoteTables();
            }
            else
            {
                $('input[name="source"]').prop('checked', false);
            }
        });
    }
    else
    {
        loadRemoteTables();
    }
}
