var selectedClassificationId = 0;
var dateFormat = "DD.MM.YYYY HH:mm";
var sortColumn = "DateModified";
var sortOrder = "DESC";

var page = -1;
var hasMoreData = true;
var itemsCount = 0;
var isLoading = false;
var length = 20;

var currentFile = {
    openFileName: "",
    openFileAttachmentId: 0,
    openFileDocumentKey: 0
};

$(document).ready(function () {
    select2withAPI();
    var applicationName = $("#ApplicationName").val();

    $("#poa-files-list").scroll(function () {
        let scrollableDiv = $(this)[0];

        if (hasMoreData === true && isLoading === false &&
            scrollableDiv.scrollTop !== 0 && scrollableDiv.scrollTop !== 1 &&
            (scrollableDiv.scrollTop + scrollableDiv.clientHeight + 1 >= scrollableDiv.scrollHeight))
        {
            getClassificationFiles(selectedClassificationId, $("#filesSearchTerm").val());
        }
    });
});

$(document).mouseup(function (e) {
    let fileSortIcon = $("#filesSortIcon");
    let fileSortBox = $("#filesSortBox");

    if (!fileSortIcon.is(e.target) && fileSortIcon.has(e.target).length === 0 &&
        !fileSortBox.is(e.target) && fileSortBox.has(e.target).length === 0) {
        fileSortBox.attr("hidden", true);
    }
});

function showClassificationFiles(classificationId, classificationAcType, classificationAcTypeDesc) {
    resetFilesPage();
    $('#file-list-heading').html(`${classificationAcType} ${classificationAcTypeDesc}`);

    if ($("#filesSearchTerm").val() !== null) {
        $("#filesSearchTerm").val("");
    }

    $('#poa-file-modal').modal({
        backdrop: false,
        show: true
    });
    getClassificationFiles(classificationId);
}

function getClassificationFiles(classificationId, searchTerm = null) {
    if (hasMoreData === false) {
        return;
    }

    isLoading = true;
    selectedClassificationId = classificationId;
    
    showPoaSpinner("poa-files-list");

    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetFilesUrl").val(),
        data: {
            classificationId: classificationId,
            searchTerm: searchTerm,
            length: length,
            start: (++page) * length,
            sortColumn: sortColumn,
            sortOrder: sortOrder
        },
        success: function (data) {            
            if (data && data.success == false) {
                handleError(data);
            }

            $(".poa-sort-option.selected").removeClass("selected");
            $("#" + sortColumn + "-" + sortOrder).addClass("selected");

            if (data && data.filesPagedResult) {
                let dataLength = data.filesPagedResult.Items.length;

                if (dataLength === 0 && page === 0) {
                    $("#no-files-message").removeAttr("hidden");
                }
                else {
                    displayItems(data.filesPagedResult.Items);
                }

                itemsCount = itemsCount + dataLength;
                if (itemsCount >= data.filesPagedResult.TotalItems) {
                    hasMoreData = false;
                }
            }
            hidePoaSpinner("poa-files-list");
            isLoading = false;
        },
        error: function (error) {
            hidePoaSpinner("poa-files-list");
            console.error(error);
            isLoading = false;
        }
    });
}

function displayItems(files) {
    const $container = $("#poa-files-list");
    files.forEach(item => {
        const $div = $('<div class="poa-file"><div style="display: inline"><i class="far fa-file-word fa-2x poa-file-icon"></i></div><div class="poa-file-item-data" style="display: inline"><div class="poa-file-name">' + item.Name + '</div><div class="poa-file-date">' + moment(item.DateCreated).format(dateFormat) + '</div></div></div >');

        $div.on('click', function () {
            getFileContent(item);
        });

        $container.append($div);
    });
}

function resetFilesPage() {
    $('#poa-files-list div').remove();
    $("#no-files-message").attr("hidden", true);

    page = -1;
    itemsCount = 0;
    hasMoreData = true;
}

let bounceTimeout;
function searchFiles() {
    clearTimeout(bounceTimeout);
    resetFilesPage();

    bounceTimeout = setTimeout(function () {
        getClassificationFiles(selectedClassificationId, $("#filesSearchTerm").val());
    }, 1000);
}

function toggleSortOptions() {
    $("#filesSortBox").attr("hidden", function (_, attr) {
        return !attr;
    });
}

function sortFiles(sortType) {
    let sortOptions = sortType.split("-");
    sortColumn = sortOptions[0];
    sortOrder = sortOptions[1];

    resetFilesPage();
    getClassificationFiles(selectedClassificationId, $("#filesSearchTerm").val());
}

function getFileContent(file) {
    showPoaSpinner("poa-files-list");

    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetFileContentUrl").val(),
        data: {
            attachmentId: file.AttachmentId,
            documentKey: file.DocumentKey
        },
        success: function (response) {
            if (response && response.success == false) {
                handleError(response);
            }

            hidePoaSpinner("poa-files-list");
            openFile(file);

            if (response && response.base64) {
                showWordFileContent(response.base64);
            }
            else {
                showNotLoadedMessage();
            }
        },
        error: function (error) {
            hidePoaSpinner("poa-files-list");
            console.error(error);
        }
    });
}

function openFile(file) {
    currentFile.openFileAttachmentId = file.AttachmentId;
    currentFile.openFileDocumentKey = file.DocumentKey;
    currentFile.openFileName = file.Name;

    showSingleFileModal();
    fillFileData(file);
    getDocumentConnections(file.DocumentAcKey);
    getDocumentMetaData(file.DocumentKey);
    setTabsContentHeight();
}

function getDocumentConnections(documentAcKey) {
    showPoaSpinner("file-connections");
    
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetDocumentConnectionsUrl").val(),
        data: {  
            documentKey: documentAcKey
        },
        success: function (data) {
            $('#file-connections').html(data);
            hidePoaSpinner("file-connections");
        },
        error: function (error) {
            console.error(error);
            hidePoaSpinner("file-connections");
        }
    });
}

function getDocumentMetaData(documentQId) {
    showPoaSpinner("file-meta-data");
    
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetDocumentMetadataUrl").val(),
        data: {
            documentQId: documentQId
        },
        success: function (data) {
            $('#file-meta-data').html(data);
            hidePoaSpinner("file-meta-data");
            select2withAPI();
         
            let laguage = getPoaCurrentLanguage();
            $('.datepicker').flatpickr({
                enableTime: true,
                dateFormat: "d.m.Y H:i",
                time_24hr: true,
                locale: laguage
            });
        },
        error: function (error) {
            console.error(error);
            hidePoaSpinner("file-meta-data");
        }
    });
}

function closeFile() {
    currentFile = {
        openFileName: "",
        openFileAttachmentId: 0,
        openFileDocumentKey: 0
    };

    clearFileData();
    resetSingleFileTabs();
    hideSingleFileModal();
}

function showSingleFileModal() {
    $("#all-files-modal").attr("hidden", true);
    $("#single-file-modal").removeAttr("hidden");

    $("#single-file-heading").html(currentFile.openFileName);
}

function hideSingleFileModal() {
    $("#single-file-modal").attr("hidden", true);
    $("#not-loaded-message").attr("hidden", true);
    $("#file-metadata").removeAttr("hidden");

    $("#save-file-btn").prop("disabled", false);
    swapLoadingIcon(false, "save-file-btn", "far fa-save");
    $("#add-file-btn").attr("hidden", true);
    swapLoadingIcon(false, "add-file-btn", "far fa-save");
    $("#save-file-btn").removeAttr("hidden");
    $("#file-name-validation").attr("hidden", true);
    $("#file-docType-validation").attr("hidden", true);
    $("#file-subject-validation").attr("hidden", true);
    $("#file-docType-subject-group").attr("hidden", true);

    $("#all-files-modal").removeAttr("hidden");
}

function resetSingleFileTabs(){
    $("#file-link-connections").removeClass("active");
    $("#file-connections").removeClass("active");
    $("#file-connections").removeClass("show");

    $("#file-link-metadata").removeClass("active");
    $("#file-meta-data").removeClass("active");
    $("#file-meta-data").removeClass("show");

    $("#file-link-info").addClass("active");
    $("#file-info").addClass("show");
    $("#file-info").addClass("active");
}

function showNotLoadedMessage() {
    $("#not-loaded-message").removeAttr("hidden");
    $("#file-metadata").attr("hidden", true);
    $("#save-file-btn").prop("disabled", true);
}

function showNewFileModal() {
    $("#all-files-modal").attr("hidden", true);
    $("#single-file-modal").removeAttr("hidden");

    $("#add-file-btn").removeAttr("hidden");
    $("#save-file-btn").attr("hidden", true);

    $("#single-file-heading").html($("#AddNewFileLoc").val());
    $("#file-name").removeAttr("readonly");
    $('#file-connections').html(null);
    $('#file-meta-data').html(null);
    $("#file-docType-subject-group").removeAttr("hidden");

    setTabsContentHeight();
    fillDefaultFileData();
}

function fillFileData(file) {
    $("#file-name").val(file.Name);
    $("#file-doc-keyview").val(file.DocumentAcKeyView);
    $("#file-created-by").val(file.UserCreated);
    $("#file-created-user").val(file.UserCreated);
    $("#file-modified-user").val(file.UserCreated);
    $("#file-created-date").val(moment(file.DateCreated).format(dateFormat));
    $("#file-modified-date").val(moment(file.DateModified).format(dateFormat));
}

function fillDefaultFileData() {
    getDocumentName()
        .then(fileName => {
            $("#file-name").val(fileName);
        })
        .catch(error => {
            $("#file-name").val("");
        });

    $("#file-created-user").val($("#CurrentUserFullName").val());
    $("#file-modified-user").val($("#CurrentUserFullName").val());
    $("#file-created-date").val(moment(new Date()).format(dateFormat));
    $("#file-modified-date").val(moment(new Date()).format(dateFormat));
    $("#file-docType-dropdown").val(null).trigger('change');
    $("#file-subject-dropdown").val(null).trigger('change');
}

function clearFileData() {
    $("#file-name").val("");
    $("#file-doc-keyview").val("");
    $("#file-created-by").val("");
    $("#file-created-user").val("");
    $("#file-modified-user").val("");
    $("#file-created-date").val("");
    $("#file-modified-date").val("");
}

function getMetaDataValues() {
    let metadata = [];
    $(".poa-metadata-item").each(function () {
        let dataObject = {};

        $(this).find('input, select').each(function () {
            if ($(this).attr('name')) {
                var inputName = $(this).attr('name').split(".")[1];
                var inputValue = $(this).val();
                dataObject[inputName] = inputValue;
            }
        });

        metadata.push(dataObject);
    });
    return metadata;
}

function validateMetadata() {
    let isValid = true;

    if ($("#file-name").val() === null || $("#file-name").val() == "" || $("#file-name").val() == undefined) {
        $("#file-name-validation").removeAttr("hidden");
        isValid = false;
    }

    $(".obligatory-input").each(function () {
        let validationField = $(this).siblings('.poa-validation').first();

        if (!$(this).val()) {
            validationField.removeAttr("hidden");
            validationField.text($("#RequiredInputLoc").val());

            isValid = false;
        }
        else {
            validationField.attr("hidden", true);
        }
    });

    if (!isValid) {
        showMessage($("#WarningLoc").val(), $("#POADataIsNotValidLoc").val());
        swapLoadingIcon(false, "save-file-btn", "far fa-save");
    }

    return isValid;
}

function updateFileContent() {
    swapLoadingIcon(true, "save-file-btn", "far fa-save");
    showPoaSpinner("file-info");

    getDocumentAsCompressed()
        .then(base64Content => {
            updateFileContentAsync(base64Content);
        })
        .catch(error => {
            hidePoaSpinner("file-info");
            console.error("Error:", error);
        });
}

function updateFileContentAsync(base64Content) {
    if (!validateMetadata()) {
        hidePoaSpinner("file-info");
        return;
    }

    let metadata = getMetaDataValues();

    $.ajax({
        cache: false,
        type: "POST",
        url: $("#UpdateFileUrl").val(),
        data: {
            attachmentId: currentFile.openFileAttachmentId,
            documentKey: currentFile.openFileDocumentKey,
            fileName: ensureDocxExtension($("#file-name").val()),
            base64Content: base64Content,
            metadata: metadata
        },
        success: function (response) {
            hidePoaSpinner("file-info");
            if (response && response.success == false) {
                handleError(response);
            }

            closeFile();
            resetFilesPage();
            getClassificationFiles(selectedClassificationId);
        },
        error: function (error) {
            hidePoaSpinner("file-info");
            swapLoadingIcon(false, "save-file-btn", "far fa-save");
        }
    });
}

function validateNewFile() {
    let isValid = true;
    $("#file-name-validation").attr("hidden", true);
    $("#file-docType-validation").attr("hidden", true);
    $("#file-subject-validation").attr("hidden", true);

    if ($("#file-name").val() === null || $("#file-name").val() == "" || $("#file-name").val() == undefined) {
        $("#file-name-validation").removeAttr("hidden");
        isValid = false;
    }

    if ($("#file-docType-dropdown").val() === null || $("#file-docType-dropdown").val() == "" || $("#file-docType-dropdown").val() == undefined) {
        $("#file-docType-validation").removeAttr("hidden");
        isValid = false;
    }

    if ($("#file-subject-dropdown").val() === null || $("#file-subject-dropdown").val() == "" || $("#file-subject-dropdown").val() == undefined) {
        $("#file-subject-validation").removeAttr("hidden");
        isValid = false;
    }

    return isValid;
}

function addNewFile() {
    if (!validateNewFile()) {
        return;
    }

    swapLoadingIcon(true, "add-file-btn", "far fa-save");
    showPoaSpinner("file-info");

    getDocumentAsCompressed()
        .then(base64Content => {
            addNewFileAsync(base64Content);
        })
        .catch(error => {
            hidePoaSpinner("file-info");
            console.error("Error:", error);
        });
}


function addNewFileAsync(base64Content) {
    $.ajax({
        cache: false,
        type: "POST",
        url: $("#AddFileUrl").val(),
        data: {
            fileName: ensureDocxExtension($("#file-name").val()),
            ClassificationId: selectedClassificationId,
            docType: $("#file-docType-dropdown").val(),
            subject: $("#file-subject-dropdown").val(),
            base64Content: base64Content
        },
        success: function (response) {
            hidePoaSpinner("file-info");
            if (response && response.success == false && response.redirectUrl) {
                window.location = response.redirectUrl;
            }

            if (response?.created == null) {
                showMessage($("#InformationLoc").val(), $("#POAFileNotCreatedLoc").val())
            }

            closeFile();
            resetFilesPage();
            getClassificationFiles(selectedClassificationId);
        },
        error: function (error) {
            hidePoaSpinner("file-info");
            swapLoadingIcon(false, "add-file-btn", "far fa-save");
        }
    });
}

function ensureDocxExtension(filename) {
    if (!filename.endsWith(".doc") && !filename.endsWith(".docx")) {
        filename += ".docx";
    }
    return filename;
}

function setTabsContentHeight() {
    var headerHeight = $('.poa-header').outerHeight();
    var modalHeaderHeight = $('#single-file-modal .modal-header').outerHeight();
    var tabsHeight = $('.poa-nav-tabs').outerHeight();
    var footerHeight = $('#single-file-modal .modal-footer').outerHeight();

    var tabsContentHeight = headerHeight + modalHeaderHeight + tabsHeight + footerHeight + 2 * 16; 
    $(".poa-tab-content").height($(window).height() - tabsContentHeight);
}

function showMessage(title, text) {
    $('#poa-message-modal').modal('show');
    $('#message-modal-title').text(title);
    $('#message-modal-text').text(text);
}

function handleError(data) {
    if (data.redirectUrl) {
        window.location = data.redirectUrl;
    }
    else {
        showMessage($("#ErrorLoc").val(), $("#GeneralErrorLoc").val());
    }
}

function getPoaCurrentLanguage() {
    let currentLanguage = $("#CurrentLanguage").val();

    switch (currentLanguage) {
        case 'SL':
            return 'sl';
        case 'HR':
            return 'hr';
        case 'RS':
        case 'SR_ME':
            return 'sr';
        case 'BA':
            return 'bs'; 
        case 'MK':
            return 'mk';
        case 'BG':
            return 'bg';
        case 'UA':
            return 'uk';
        case 'RU':
            return 'ru';
        case 'RO':
            return 'ro'; 
        case 'IT':
            return 'it';
        case 'DE':
        case 'AT':
            return 'de';
        default:
            return 'default'; // Default to English if no match

        // EN and EU are English
        // KO and AQ - there is no Albanian translations for now
    }
}