/**
 * Get tables.
 *
 * @access public
 * @return void
 */
function changeTables()
{
    var datatype = $('#datatype').val();
    if(!datatype) return;

    var $source = $('#source');
    $.get(createLink('datasource', 'ajaxGetDatasource', 'type=' + datatype), function(data)
    {
        var picker = $('#source').data('zui.picker');
        if(picker) picker.destroy();
        $source.html(data).picker();

        /* Trigger it manually. */
        loadTables();
    });
}

/**
 * Set picker width.
 *
 * @access public
 * @return void
 */
function setPickerWidth()
{
    /* Set picker width. */
    $('#typesource').find('.picker-single').first().css('width', '30%');
    $('#typesource').find('.picker-single').last().css('width', '70%');

    var datatype = $('#datatype').val();
    if($('#sourcetype_upload').is(':checked') || datatype == 'excel')
    {
        /* Destroy tabletype. */
        var $tabletype = $('#tabletype').data('zui.picker');
        if($tabletype) $tabletype.destroy();

        $('#tablesource').find('.picker-single:visible').first().css('width', '100%');
    }
    else if(datatype == 'mysql' || datatype == 'pgsql')
    {
        /* Init tabletype. */
        $('#tabletype').picker();

        $('#tablesource').find('.picker-single').first().css('width', '30%');
        $('#tablesource').find('.picker-single').last().css('width', '70%');
    }
}

/**
 * Load tables.
 *
 * @access public
 * @return void
 */
function loadRemoteTables(callback)
{
    var sourceID = $('#source').val();
    if(!sourceID) return;

    var $table = $('#table');
    $table.empty().trigger('chosen:updated');

    var datatype = $('#datatype').val();
    if(datatype == 'excel')
    {
        var link = createLink('datasource', 'ajaxGetTables', 'sourceID=' + sourceID);
        $.get(link, function(data)
        {
            var picker = $('#table').data('zui.picker');
            if(picker) picker.destroy();
            $table.html(data).picker();
            setPickerWidth();
            callback && callback();
        });
    }
    else if(datatype == 'mysql' || datatype == 'pgsql')
    {
        $('#tabletype').show();
        $('#tabletype').next().show();

        var tabletype = $('#tabletype').val();
        if(!tabletype) return;

        var link = createLink('datasource', 'ajaxGetTablesOrViews', 'sourceID=' + sourceID + '&tabletype=' + tabletype + '&select=true');
        $.get(link, function(data)
        {
            var picker = $('#table').data('zui.picker');
            if(picker) picker.destroy();
            $table.html(data).picker();
            setPickerWidth();
            callback && callback();
        });
    }
}


/** Load tables from local excel file */
function loadLocalTables(callback)
{
    if($('[name="sourcetype"]:checked').val() !== 'upload') return;

    $('#tabletype').hide();
    $('#tabletype').next().hide();

    var file = $('#file')[0].files[0];
    if(!file) return;
    var reader = new FileReader()
    reader.onload = function(ev)
    {
        var $table   = $('#table').empty();
        var picker = $table.data('zui.picker');
        if(picker) picker.destroy();
        $table.empty();

        var data     = ev.target.result;
        var workbook = XLSX.read(data);
        for(var index in workbook.SheetNames)
        {
            var sheetName = workbook.SheetNames[index];
            if(sheetName == 'CB_DATA_') continue;

            $table.append($('<option/>').attr({title: sheetName, value: index}).text(sheetName));
        }

        $table.picker();

        setPickerWidth('upload');
        callback && callback();
    };
    reader.readAsArrayBuffer(file);
}

function loadTables()
{
    var sourceType = $('[name="sourcetype"]:checked').val();
    var fileElement = document.getElementById('file');
    var sourceFile = fileElement ? fileElement.files[0] : null;
    var sourceShow = $('#sourceSelectRow:visible').length > 0;
    var needShowTable = (sourceType === 'upload' && sourceFile) || (sourceShow && $('#source').val());
    $('#tableSelectRow').toggleClass('hidden', !needShowTable);
    if(needShowTable)
    {
        $('#table').empty().trigger('chosen:updated');
        if(sourceType === 'upload')
        {
            loadLocalTables();
        }
        else
        {
            loadRemoteTables();
        }
        setPickerWidth(sourceType);
    }
}

/**
 * Update sources
 *
 * @access public
 * @return void
 */
function updateSources()
{
    var $source = $('#source');
    if($source.data('projectID') === projectID) return;

    $source.empty().append('<option value="" selected />');
    var sources = (project ? project.sources : null) || [];
    sources.forEach(function(source)
    {
        $source.append($('<option/>').attr({title: source.name, value: source.id}).text(source.name));
    });
    $source.trigger('chosen:updated');
}

$(function()
{
    $('#createproject').on('change', function()
    {
        var isCreateProject = $(this).is(':checked');
        $('#dataform').toggleClass('is-create-project', isCreateProject);
        $('#sourcetypesCell').val('upload');
        updateSources();
        $('#projectname').focus();
    });

    $('#sourcetypesCell').on('change', function()
    {
        $('#dataform').toggleClass('is-select-source', $(this).find('[name="sourcetype"]:checked').val() === 'select');
        loadTables();
    });

    $('#datatype').on('change', changeTables);
    $('#file').on('change', loadTables);

    $('#fileInput').fileInput({onDelete: function()
    {
        $('#file').val('');
    }});

    $('.file-input-delete').click(function(){
        $('#tableSelectRow').toggleClass('hidden', true);
    });

});

