Dropzone.autoDiscover = false;
Dropzone.options.Saeeddropzone = false;

function getImageOrIconForThumbnail(url = "") {

    const path = url.split('?')[0]; // Remove query params
    const extMatch = path.match(/\.([a-zA-Z0-9]+)$/);
    const ext = extMatch ? extMatch[1].toLowerCase() : "";

    const imageExtensions = ["jpg", "jpeg", "png", "gif", "webp", "bmp", "svg", "tiff"];

    if (imageExtensions.includes(ext)) {
        return `<img class="img-preview" src="${url}" />`;
    }

    const iconMap = {
        zip: { color: "#9346ff", icon: "ph-file-zip" },
        pdf: { color: "#467CFF", icon: "ph-file-pdf" },
        mp3: { color: "#0c8185", icon: "ph-file-audio" },
        sql: { color: "#619580", icon: "ph-file-sql" },
        jks: { color: "#29b5b5", icon: "ph-key" },
        mp4: { color: "#ca3f3f", icon: "ph-file-video" }
    };

    if (iconMap[ext]) {
        const { color, icon } = iconMap[ext];
        return `<i style="color:${color}" class="fileExt ph ${icon}"></i>`;
    }

    // Default icon
    return `<i style="color:#5e5f6a" class="fileExt ph ph-file"></i>`;
}

$(function () { // start of document ready:

    $(".copy-file-link").click(function () {

        let link = $(this).data('link');
        copyToClipboard(link, "لینک فایل کپی شد");

    });

    $(".fm-delete-folder").click(function () {

        let deleteBtn = $(this);
        let foldername = deleteBtn.data('foldername');

        Swal.fire({
            title: 'حذف پوشه و محتوای آن',
            iconHtml: '<i class="ph ph-download"></i>',
            text: 'آیا از حذف کامل پوشه ' +foldername+ ' و تمام محتوای داخل آن مطمئنید؟',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#007bff',
            confirmButtonText: 'حذف کامل',
            cancelButtonText: 'انصراف',
            showClass: {popup: 'animated fadeInUp faster'},
            hideClass: {popup: 'animated fadeOutDown faster'},
        }).then((result) => {
            if (result.isConfirmed) {

                let url = window.location.href;
                let path = deleteBtn.data('path');
                url += '?delete-folder='+path;   
                window.location.href = url;

            }

        });

        return false;

    });

    $(".fm-delete-file").click(function () {

        let deleteBtn = $(this);
        let filename = deleteBtn.data('filename');

        Swal.fire({
            title: 'حذف فایل',
            icon: 'warning',
            text: 'آیا از حذف فایل '+filename+' مطمئن هستید؟',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#007bff',
            confirmButtonText: 'حذف',
            cancelButtonText: 'انصراف',
            showClass: {popup: 'animated fadeInUp faster'},
            hideClass: {popup: 'animated fadeOutDown faster'},
        }).then((result) => {
            if (result.isConfirmed) {

                let url = window.location.href;
                let path = deleteBtn.data('path');
                url += '?delete-file='+path;   
                window.location.href = url;

            }

        });

        return false;

    });

    $(".fm-rename-filefolder").click(async function (e) {

        e.preventDefault();

        let renameBtn = $(this);
        let ffname = renameBtn.data('name');
        let ffpath = renameBtn.data('path');
        let ffpath_no_name = renameBtn.data('path-nn');

        const { value: newName } = await Swal.fire({
            input: 'text',
            inputLabel: 'تغییر نام ' + ffname,
            title: 'تغییر نام',
            html: 'تغییر نام ' + ffname + '<br><br><div class="infos">تغییر نام فولدر و فایل، آدرس دسترسی به آن را تغییر میدهد و در صورتی که از آن در برنامه استفاده کرده‌اید باعث لود نشدن آن خواهد شد.</div>',
            customClass: 'rename-ff-input',
            inputPlaceholder: 'Enter new file or folder name',
            inputValue: ffname,
            showCancelButton: true,
            confirmButtonText: 'ذخیره',
            cancelButtonText: 'انصراف',
            showClass: {popup: 'animated fadeInUp faster'},
            hideClass: {popup: 'animated fadeOutDown faster'},
        });

        if(newName === "") notyf.error("داده‌ای وارد نشده است");
        if (newName) {
            let url = window.location.href;
            url += '?rename-file-folder='+ffpath + '&pathnn=' + ffpath_no_name + '&newname=' + newName;   
            window.location.href = url;
        }

        return false;

    });

    $("#create-folder").click(async function (e) {

        e.preventDefault();

        let createFolderBtn = $(this);
        let path = createFolderBtn.data('path');

        const { value: folderName } = await Swal.fire({
            input: 'text',
            inputLabel: 'ایجاد پوشه',
            title: 'ایجاد پوشه',
            html: 'ایجاد یک پوشه در مسیر ' + path,
            customClass: 'rename-ff-input',
            inputPlaceholder: 'Enter folder name',
            inputValue: "",
            showCancelButton: true,
            confirmButtonText: 'ایجاد',
            cancelButtonText: 'انصراف',
            showClass: {popup: 'animated fadeInUp faster'},
            hideClass: {popup: 'animated fadeOutDown faster'},
        });
          
        if(folderName === "") notyf.error("داده‌ای وارد نشده است");
        if (folderName) {
            let url = window.location.href;
            url += '?create-folder='+path + '&folder-name=' + folderName;   
            window.location.href = url;
        }

        return false;

    });

    $("#upload-file").click(function () {

        $('#fm-upload-view').fadeIn('fast');
        let path = $('#folder-path').data('path');

    });

    $("#upload-back-btn").click(function () {

        //$('#fm-upload-view').fadeOut('fast');

        // Reload whitout page query
        let url = new URL(window.location.href);
        url.searchParams.delete('page');
        window.location.href = url.toString();
        return false;

    });
    
    let path = $('#folder-path').data('path');
    $('#fm-dropzone').dropzone({
        url: mpPanelBaseUrl + "/general-file-uploader",
        paramName: "file",
        params: {'folder':path},
        maxFilesize: 10000, // MB
        maxFiles: 20,
        timeout: 600000,
        success: function (file, response) {
            notyf.success("آپلود با موفقیت انجام شد");
        },
    });

    $("#fm-search-btn").click(function () {

        let searchQuery = $('#fm-search').val();
        if(searchQuery != ""){
            let url = new URL(window.location.href);
            url.searchParams.set('search', searchQuery);
            url.searchParams.set('page', 1);
            window.location.href = url.toString();
        }else{
            notyf.error("مقدار جستجو خالی است");
        }

    });

    $("#fm-remove-search-btn").click(function () {
        var uri = window.location.href.toString();
        if (uri.indexOf("?") > 0) {
            var clean_uri = uri.substring(0, uri.indexOf("?"));
            window.location.href = clean_uri;
        }
    });

});