/**
* 2007-2024 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2024 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*
* Don't forget to prefix your containers with your own identifier
* to avoid any conflicts with others containers.
*/
$(document).ready(function() {
    $("#btn_csv_url").click(function(){
        $("#csv_files_url").show();
        $("#csv_files_url_header").show();
        $("#csv_file_options").hide();
    });

    $("#btn_remove_csv_url").click(function(){
        $("#csv_files_url").hide();
        $("#csv_files_url_header").hide();
        $("#csv_file_options").show();
    });

    $("#btn_get_csv_url").click(function(e){
        e.preventDefault();
        $.ajax({
            url: ajax_csv_url,
            data: {
                csv_url: $("#csv_url").val()
            },
            dataType: 'json',
            success: function(json){
                if (json) {
                    $('#csv_selected_value').val(json);
                }
                location.reload();
            },
            error: function(j){
            }
        });
    });

    var file_add_button = Ladda.create(document.querySelector('#file-add-button'));
    var file_total_files = 0;

    $('#file').fileupload({
        dataType: 'json',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(csv|xls|xlsx)$/i,
        singleFileUploads: true,
        maxFileSize: post_max_size,
        start: function (e) {
            file_add_button.start();
        },
        fail: function (e, data) {
            $('#file-errors').html(data.errorThrown.message).show();
        },
        done: function (e, data) {
            if (data.result) {
                if (typeof data.result.file !== 'undefined') {
                    if (typeof data.result.file.error !== 'undefined' && data.result.file.error != '')
                        $('#file-errors').html('<strong>'+data.result.file.name+'</strong> : '+data.result.file.error).show();
                    else {
                        $(data.context).find('button').remove();

                        var filename = encodeURIComponent(data.result.file.filename);
                        var row = $('#csv_uploaded_history tr:first').clone();

                        $('#csv_uploaded_history').append(row);
                        row.removeClass('hide');
                        row.find('td:first').html(data.result.file.filename);
                        row.find('button.csv-use-btn').data('filename', data.result.file.filename);
                        row.find('a.csv-download-link').attr('href',importtools_url + "?csvfilename=" + filename);
                        row.find('a.csv-delete-link').attr('href',importtools_url + "?csvfilename="+filename+'&delete=1');
                        csv_select(data.result.file.filename);
                        var items = $('#csv_uploaded_history tr').length -1;
                        $('.csv-history-nb').html(items);
                        enableHistory();
                    }
                }
            }
        },
    }).on('fileuploadalways', function (e, data) {
        file_add_button.stop();
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,	file = data.files[index];

        if (file.error) {
            $('#file-errors').append('<strong>'+file.name+'</strong> ('+humanizeSize(file.size)+') : '+file.error).show();
            $(data.context).find('button').trigger('click');
        }
    });

    $('#csv_uploaded_history').on('click', 'button.csv-use-btn', function(e){
        e.preventDefault();
        var filename = $(this).data('filename');
        csv_select(filename);
    });
    $('#file-add-button').on('click', function(e) {
        e.preventDefault();
        $('#file-success').hide();
        $('#file-errors').html('').hide();
        $('#file').trigger('click');
    });
    $('#file-remove-button').on('click', function(e) {
        e.preventDefault();
        csv_unselect();
    });

    $('.csv-history-btn').on('click',function(e){
        e.preventDefault();
        $('#csv_files_history').toggle();
        $('#csv_file_uploader').toggle();
    })
    //show selected csv if exists
    var selected = '{$csv_selected}';
    if(selected){
        $('#csv_file_selected').show();
        $('#csv_file_uploader').hide();
    }

    enableHistory();

    $('#preview_import').submit(function(e) {
        if ($('#truncate').get(0).checked) {
            if (truncateAuthorized) {
                if (!confirm(confirm_msg + ' ' + $.trim($('#entity > option:selected').text().toLowerCase()) + '?'))
                    e.preventDefault();
            }
            else {
                agile_show_message(nopermission_msg);
                return false;
            }
        }
    });

    $("select#entity").change(function() {
        if ($("#entity > option:selected").val() == 8 || $("#entity > option:selected").val() == 9 || AST_PRODUCT_IMPORT_ALLOW_DELETE == 0) {
            $("#truncate").closest('.form-group').hide();
        }
        else {
            $("#truncate").closest('.form-group').show();
        }
        if ($("#entity > option:selected").val() == 9) {
            $(".import_supply_orders_details").show();
        }
        else {
            $(".import_supply_orders_details").hide();
            $('input[name=multiple_value_separator]').val(multiple_value_separator_selected);
        }
        if ($("#entity > option:selected").val() == 1) {
            $("#match_ref").closest('.form-group').show();
        }
        else {
            $("#match_ref").closest('.form-group').hide();
        }
        if ($("#entity > option:selected").val() == 1 || $("#entity > option:selected").val() == 0) {
            $(".import_products_categories").show();
        }
        else {
            $(".import_products_categories").hide();
        }
        if ($("#entity > option:selected").val() == 0 || $("#entity > option:selected").val() == 1 ||
            $("#entity > option:selected").val() == 5 || $("#entity > option:selected").val() == 6) {
            $("#regenerate").closest('.form-group').show();
        }
        else {
            $("#regenerate").closest('.form-group').hide();
        }
        if( (	$("#entity > option:selected").val() == 0 || $("#entity > option:selected").val() == 1 ||
                $("#entity > option:selected").val() == 3 || $("#entity > option:selected").val() == 5 ||
                $("#entity > option:selected").val() == 6 || $("#entity > option:selected").val() == 7
            ) && AST_PRODUCT_IMPORT_ALLOW_FORCE_ID == 1
          )
        {
            $("#forceIDs").closest('.form-group').show();
        }
        else {
            $("#forceIDs").closest('.form-group').hide();
        }

        $("#entitie").html($("#entity > option:selected").text().toLowerCase());

        // $.ajax({
        //     url: base_dir_ssl + 'modules/agilemultipleseller/ajax.php',
        //     data: {
        //         getAvailableFields:1,
        //         entity: $("#entity").val()
        //     },
        //     dataType: 'json',
        //     success: function(j){
        //         var fields = "";
        //         $("#availableFields").empty();

        //         for (var i = 0; i < j.length; i++)
        //             fields += j[i].field;

        //         $("#availableFields").html(fields);
        //         $('.help-tooltip').tooltip();
        //     },
        //     error: function(j){}
        // });
    });

    $("select#entity").trigger('change');

    $('#file-selectbutton').click(function(e){
        $('#file').trigger('click');
    });
    $('#filename').click(function(e){
        $('#file').trigger('click');
    });
    $('#file').change(function(e){
        var val = $(this).val();
        var file = val.split(/[\\/]/);
        $('#filename').val(file[file.length-1]);
    });
});

function humanizeSize(bytes) {
    if (typeof bytes !== 'number')
        return '';
    if (bytes >= 1000000000)
        return (bytes / 1000000000).toFixed(2) + ' GB';
    if (bytes >= 1000000)
        return (bytes / 1000000).toFixed(2) + ' MB';
    return (bytes / 1000).toFixed(2) + ' KB';
}
// when user select a .csv
function csv_select(filename) {
    $('#csv_selected_value').val(filename);
    $('#csv_selected_filename').html(filename);
    $('#csv_file_selected').show();
    $('#csv_file_uploader').hide();
    $('#csv_files_history').hide();
}
// when user unselect the .csv
function csv_unselect() {
    $('#csv_file_selected').hide();
    $('#csv_file_uploader').show();
}

// add a disabled state when empty history
function enableHistory(){
    if($('.csv-history-nb').text() == 0){
        $('button.csv-history-btn').attr('disabled','disabled');
    } else {
        $('button.csv-history-btn').attr('disabled',false);
    }
}
