import $, {ajax} from "jquery";
import Dropzone from 'dropzone';

interface DropzoneFileWithServerId extends Dropzone.DropzoneFile {
    serverId?: string;
}

$(function () {


    $(".dz-button").removeClass("dz-button").addClass("btn btn-light dz-cust");
    $('#submitbutton').prop("disabled", true);

    if (window.location.href.indexOf("/de/") > -1) {
        $(".dz-cust").html("<i class=\"icofont-plus-circle f-22\"></i> <span style='font-size: 26px'> Dateien hochladen</span>");
    }

    if (window.location.href.indexOf("/en/") > -1) {
        $(".dz-cust").html("<i class=\"icofont-plus-circle f-22\"></i> <span style='font-size: 22px'> Upload Files</span>");
    }

    if (window.location.href.indexOf("/es/") > -1) {
        $(".dz-cust").html("<i class=\"icofont-plus-circle f-22\"></i> <span style='font-size: 26px'> Cargar archivos</span>");
    }

    if (window.location.href.indexOf("/ru/") > -1) {
        $(".dz-cust").html("<i class=\"icofont-plus-circle f-22\"></i> <span style='font-size: 26px'> Загрузка файлов</span>");
    }

    $('#shared_file_contact').on('change', function() {
        checkFormState();
    });

    $('#chooseUserFree').on('input', function() {
        checkFormState();
    });


    $('#shared_file_title, #shared_file_message').on('input', function () {
        checkFormState();
    });

    $('#shared_file_contactEmail').on('input', function () {
        checkFormState();
    });
})

const license: string = $('#aLXq676F8V6arDsukGLrsnKkdvc7Jv5TKu9F6aSWaVaVaujkmF').val() as string

//o9zZ
//mdzPzA==
let maxFilesizeVal = 3000;
let maxFilesizeValShow = Number(maxFilesizeVal / 1000) + ' GB'
if (license == 'o9zZ') {
    maxFilesizeVal = 200000
    maxFilesizeValShow = Number(maxFilesizeVal / 1000) + ' GB'
}
$('#maxUploadSize').text(maxFilesizeValShow)
//alert(maxFilesizeVal)
Dropzone.options.docUpload = {
    maxFilesize: maxFilesizeVal,
    addRemoveLinks: true,
    dictCancelUpload: '<i class="icofont-stop icofont-2x" style="position: absolute; cursor: pointer; margin-top: -20px; margin-left: -15px; z-index: 10000"></i>',
    dictRemoveFile: "<i class=\"d-none d-md-block icofont-delete-alt icofont-2x text-danger\" style=\"position: absolute; cursor: pointer; margin-top: -28px; margin-left: 45px;z-index: 10000\"></i><svg class='d-block d-md-none' style=' position: absolute; margin-left: -26px; cursor: pointer; z-index: 10000;' width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M18 6L6 18\" stroke=\"white\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M6 6L18 18\" stroke=\"white\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>\n",
    init: function () {
        this.on("success", function (file: DropzoneFileWithServerId, response: any) {
            file.serverId = response.id;
            $('.dz-default').show()
            $('.dz-cust').show()
            //$('#uploader').hide();
            //$('#uploadData').show();
            //$('#submitbutton').prop("disabled",false);
            $(file.previewElement).find('.dz-success-mark').remove();
            $('#the-progress-div').hide();
            updateFileVisibility();
            checkFormState();
        });
        this.on("sending", function (file, xhr, formData) {
            $('#the-progress-div').show();
            $('#submitbutton').prop("disabled", true);
            //$('#uploader').show();
            //$('#uploadData').hide();
        });
        this.on("totaluploadprogress", function (progress) {
            $("#the-progress-div").width(progress.toFixed(0) + '%');
            $(".the-progress-text").text(progress.toFixed(0) + '%');
            //$('#submitbutton').prop("disabled",false);
        });
        this.on("removedfile", function (file: DropzoneFileWithServerId) {
            const locale = window.location.pathname.split('/')[2];
            const url = `/app/${locale}/upload/${file.serverId}/remove`;
            console.log('newee');
            ajax({
                method: 'POST',
                url: url,
                success: function (response: any) {
                    if (response.success === true) {
                        updateFileVisibility();
                        checkFormState();
                    }
                },
            });
        });
    }
};


const fileContainer = $('#docUpload');  // Указание на форму с id "docUpload"
const toggleButton = $('<button id="toggleFiles" class="toggle-files" type="button" style="display: none;">Show more</button>');
fileContainer.after(toggleButton);

function updateFileVisibility() {
    const filePreviews = fileContainer.find('.dz-preview');

    if (!fileContainer.hasClass('show-all')) {
        filePreviews.each(function (index) {
            if (index >= 3) {
                $(this).addClass('d-none');
            } else {
                $(this).removeClass('d-none');
            }
        });
    }


    if (filePreviews.length > 3) {
        toggleButton.show();
        if (!fileContainer.hasClass('show-all')) {
            toggleButton.text('Show more');
        }
    } else {
        toggleButton.hide();
    }
}

toggleButton.on('click', function () {
    if (fileContainer.hasClass('show-all')) {
        fileContainer.removeClass('show-all');
        fileContainer.find('.dz-preview').each(function (index) {
            if (index >= 3) {
                $(this).addClass('d-none');
            }
        });
        toggleButton.text('Show more');
    } else {
        fileContainer.addClass('show-all');
        fileContainer.find('.dz-preview').removeClass('d-none');
        toggleButton.text('Hide');
    }
});

function checkFormState() {
    const userSelected = $('#shared_file_contact').val() || $('#chooseUserFree').val();
    const filesUploaded = fileContainer.find('.dz-preview').length > 0;
    const emailSelected = String($('#shared_file_contactEmail').val()).trim() !== '';


    // Приведение значений к строке и использование метода trim
    const titleFilled = String($('#shared_file_title').val()).trim() !== '';
    const messageFilled = String($('#shared_file_message').val()).trim() !== '';


    if (filesUploaded && titleFilled && messageFilled) {
        if(userSelected || emailSelected ) {
            $('#submitbutton').prop("disabled", false);
            return true;
        }
    } else {
        $('#submitbutton').prop("disabled", true);
        return false;
    }
}