var passwordEntropy = 0;

function initializeCompanyCompany() {
    dropifyUpload();
    outServerDisplayServiceData();

    $(".datepicker").datepicker({
        format: 'dd.mm.yyyy',
        language: $('#siteLocale').val()
    }).on('changeDate', function () {
        $(this).datepicker('hide');
    });

    initializePartnerTypeahead($('#Company').attr('dataUrl'), $('#Company'), $("#CompanyId"), function (item) {
        $("#IsCompanyVat").val(item.isVAT);

        $("#iris6971Modal").modal("show");
    });

    $('#Company').on("blur", function () {
        if ($('#Company').val() !== $("#CompanyId").val()) {
            $('#Company').val($("#CompanyId").val());
        }
    });

    $('#IsCompanyVatSwitch').on("change", function () {
        $("#IsCompanyVat").val($(this).is(':checked'));
        $("#IsCompanyVatDisplaySwitch").val($(this).is(':checked'));
        $('#IsCompanyVatDisplaySwitch').removeAttr("disabled");
        $('#IsCompanyVatDisplaySwitch').trigger('click');
    });

    var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
    elems.forEach(function (html) {
        var switchery = new Switchery(html, { size: 'small' });
    });

    $('.edit-form-button').on('click', function () {
        var form = $(this).closest('form');

        form.find('.form-display-element').css('display', 'none');
        form.find('.form-edit-element').css('display', 'block');
    });

    $('.cancel-button').on('click', function () {
        var form = $(this).closest('form');

        var displayElements = form.find('.form-display-element');
        $.each(displayElements, function () {
            var editElement = $(this).closest('td').find('.form-edit-element');
            if (editElement) {
                if ($(this).closest('td').find('input').hasClass('js-switch-small')) {
                    var swtich = document.querySelector('#' + $(this).closest('td').find('input').attr('id'));
                    if (($(this).html() === $('#YesLoc').val() && !swtich.checked) || ($(this).html() === $('#NoLoc').val() && swtich.checked)) {
                        $('.js-switch-small').trigger('click');
                    }
                } else if ($(this).closest('td').find('input').attr('type') === 'file') {
                    $(this).closest('td').find('input').val("");
                } else {
                    $(this).closest('td').find('input').val($.trim($(this).html()));
                }
            }
        });

        form.find('.form-display-element').css('display', 'block');
        form.find('.form-edit-element').css('display', 'none');
    });

    var url = new URL(window.location.href);
    var enterGoogleApiKey = decodeURI(url.searchParams.get("enterGoogleApiKey"));
    if (enterGoogleApiKey === "True" || enterGoogleApiKey === true) {
        $("#GoogleApiKey").focus();
    }
}

async function saveCompanyData(testConnection, killPaas = false) {
    var fa2required = paw.utils.value.strToBool($('#FA2required').val());
    if (fa2required) {
        console.error("Action authorization required");
        return;
    }

    var form = $("#companyForm");
    var formData = new FormData($("#companyForm")[0]);
    formData.set('OutServerTimeout', $("#OutServerTimeout").val() ? (toNumber($("#OutServerTimeout").val()) * 1000) : 0);
    formData.set('OutServerUseSASL', $("#OutServerUseSASL").is(":checked"));
    formData.set('OutServerForceTLS12', $("#OutServerForceTLS12").is(":checked"));
    formData.set('OutServerUseTLS', $("#OutServerUseTLS").is(":checked"));
    formData.set('OutServerUseEHLO', $("#OutServerUseEHLO").is(":checked"));
    formData.set('OutServerUsePOP3Login', $("#OutServerUsePOP3Login").val() === "on");
    formData.set('OutServerUseSASL', $("#OutServerUseSASL").val() === "on");
    formData.set('OutServerUseSSLTLS', $("#OutServerUseSSLTLS option:selected").val());
    formData.set('MaxCashPayment', formatDisplay(2, $("#MaxCashPayment").val(), true));

    $("#saveButton i").addClass("fa-spin fa-spinner").removeClass("fa-save");

    await fetch(form.attr('action'), {
        method: "POST",
        body: formData,
    }).then((data) => data.json()
    ).then(async (data) => {
        if (data.Success === true) {
            var editElements = form.find('.form-edit-element');
            $.each(editElements, function () {
                var displayElement = $(this).closest('td').find('.form-display-element');
                if (displayElement) {
                    if ($(this).find('input').attr('type') === 'file') {
                        if ($(this).find('input').val() !== '') {
                            var file = $('.dropify-render').find('img:first').attr('src');
                            $("#CompanyLogo").attr('src', file);
                            $(this).find('input').val("");
                        }
                    } else if ($(this).closest('td').find('.form-display-element').hasClass("textArea")) {
                        $(this).closest('td').find('textarea').val($(this).closest('td').find('.form-edit-element textarea').val());
                    } else if (!$(this).find('input').hasClass('js-switch-small')) {
                        $(this).closest('td').find('.form-display-element').html($(this).find('input').val());
                    }
                }
            });

            form.find('.form-display-element').css('display', 'block');
            form.find('.form-edit-element').css('display', 'none');

            // update initial values after successfull save
            form.find('[data-initial-value]').each(function () {
                var $elt = $(this);
                $elt.attr('data-initial-value', $elt.val());
            });
            

            if (testConnection === "true")
                testOutServerConnection();
            else if (killPaas === true) {
                $.get($("#KillPaas").val(), function (response) {
                    if (!response) {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: $("#GeneralError").val(),
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: $("#OkLoc").val(),
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    }
                });
            }
        }
        else {
            $("#errorModalMessage").html(data.Error);
            $("#errorModal").modal('show');
        }
        $("#saveButton i").removeClass("fa-spin fa-spinner").addClass("fa-save");
    }).catch((error) => {
        $("#saveButton i").removeClass("fa-spin fa-spinner").addClass("fa-save");
        $("#errorModalMessage").html(error);
        $("#errorModal").modal('show');
    });
}

function openServerDataModal($fiscalServer, $fiscalTaxServer, $fiscalCheckConnectionServer, title, tableTitles, rowTitles) {
    let serverLines = "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[0] + "</td><td class='no-padding'><input id='fiscalServer_dataModal' class='form-control' value='" + $fiscalServer.val() + "' /></td></tr>";
    serverLines += "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[1] + "</td><td class='no-padding'><input id='fiscalTaxServer_dataModal' class='form-control' value='" + $fiscalTaxServer.val() + "' /></td></tr>";
    serverLines += "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[2] + "</td><td class='no-padding'><input id='fiscalCheckConnectionServer_dataModal' class='form-control' value='" + $fiscalCheckConnectionServer.val() + "' /></td></tr>";

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "modal",
        title: title,
        content: "<table class='table table-bordered'><thead><tr><th width='20%'>" + tableTitles[0] + "</th><th width='80%'>" + tableTitles[1] + "</th></tr></thead><tbody>" + serverLines + "<tbody></table>",
        buttons: [
            {
                text: $("#OkLoc").val(),
                icon: 'fa fa-check',
                type: 'primary',
                closeOnAction: true,
                action: function () {
                    $fiscalServer.val($("#fiscalServer_dataModal").val());
                    $fiscalTaxServer.val($("#fiscalTaxServer_dataModal").val());
                    $fiscalCheckConnectionServer.val($("#fiscalCheckConnectionServer_dataModal").val());
                    $fiscalServer.closest("form").find(".buttons-tabbed button[type='submit']").click();
                }
            }
        ]
    });
}

function openFiscalDateModal($fiscalDate, $fiscalDateNew, title, tableTitles, rowTitles) {
    var dateNewVal = $fiscalDateNew.val();
    let tableRows = "<tr><td class='no-padding'><input id='fiscalDate_dataModal' class='form-control datepicker'" + (dateNewVal.length > 0 ? " disabled" : "") + " value='" + $fiscalDate.val() + "' /></td><td class='nowrap-text disabled-col'>" + rowTitles[0] + "</td></tr>";
    tableRows += "<tr><td class='no-padding'><input id='fiscalDateNew_dataModal' class='form-control datepicker' value='" + dateNewVal + "' /></td><td class='nowrap-text disabled-col '>" + rowTitles[1] + "</td></tr>";

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "modal",
        title: title,
        width: "20%",
        minWidth: "400px",
        id: "fiscalDateModal",
        onOpen: function () {
            $('#fiscalDateModal').find(".datepicker").datepicker({
                format: 'dd.mm.yyyy',
                language: $('#siteLocale').val()
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });
        },
        content: "<table class='table table-bordered'><thead><tr><th width='50%'>" + tableTitles[0] + "</th><th width='50%'>" + tableTitles[1] + "</th></tr></thead><tbody>" + tableRows + "<tbody></table>",
        buttons: [
            {
                text: $("#OkLoc").val(),
                icon: 'fa fa-check',
                type: 'primary',
                closeOnAction: true,
                action: function () {
                    console.log($fiscalDate, $fiscalDate.closest("form"));
                    $fiscalDate.val($("#fiscalDate_dataModal").val());
                    $fiscalDateNew.val($("#fiscalDateNew_dataModal").val());
                    $fiscalDate.closest("form").find(".buttons-tabbed button[type='submit']").click();
                }
            }
        ]
    });
}

function checkFiscalServerConnectivity() {
    $("#checkFiscalServerConnectivityBtn").find("i").removeClass("fa-wifi").addClass("fa-spinner fa-spin");

    $.post($("#UrlCheckFiscalServiceConnectivity").val(), {
        FiscalServer: $("#FiscalServer").val()
    }).done(function (isServiceAvailable) {
        if (isServiceAvailable) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "success",
                text: $("#ConnectionCheckSuccessLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#OkLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
        else {
            showError($("#ConnectionCheckFailedLoc").val());
        }
        $("#checkFiscalServerConnectivityBtn").find("i").addClass("fa-wifi").removeClass("fa-spinner fa-spin");
    }).fail(function () {
        showError($("#ErrorHappenedWhileCheckingFiscalServiceConnectivityLoc").val());
        $("#checkFiscalServerConnectivityBtn").find("i").addClass("fa-wifi").removeClass("fa-spinner fa-spin");
    });
}


function showError(text) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "error",
        text: text,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#OkLoc").val(),
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function convertToBase64(file, element) {
    var reader = new FileReader();
    reader.onload = function () {
        var img = new Image;
        img.onload = function () {
            element.attr('src', reader.result);
            element.css((img.width > img.height ? 'max-width' : 'max-height'), '300px').css((img.width > img.height ? 'max-height' : 'max-width'), 'none');
        };

        img.src = reader.result;
    };

    reader.readAsDataURL(file);
}

function dropifyUpload() {
    $('.dropify').dropify({
        messages: {
            'default': $("#DragAndDropOrClick").val(),
            'replace': $("#DragAndDropOrClick").val(),
            'remove': $("#Remove").val(),
            'error': $("#GeneralErrorMessage").val()
        },
        error: {
            'imageFormat': $("#WrongImageFormat").val()
        }
    });
}

function openPasswordVerificationModal() {
    $().customModal({
        showCloseButton: true,
        closeOtherModals: false,
        height: "40%",
        maxHeight: "300px",
        width: "40%",
        maxWidth: "500px",
        type: "modal",
        id: "verifyPasswordModal", 
        help: "helpUrl", //
        title: $("#CustomComplexityLoc").val(),
        content: $("#password-vefirication-modal").html(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#CancelLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-key',
                text: $("#UseComplexityLoc").val(),
                action: async function () {
                    useComplexity();
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });

    let debounceDelay = 200;
    let debounceTimer;

    $('.custom-modal #password-check-input').on('input', function() {
        clearTimeout(debounceTimer);

        debounceTimer = setTimeout(function () {
            checkComplexity();
        }, debounceDelay);
    });

    $(".custom-modal #togglePassword").click(function () {
        var passwordField = $(".custom-modal #password-check-input");
        var fieldType = passwordField.attr("type");

        if (fieldType === "password") {
            passwordField.attr("type", "text");
            $(this).removeClass("fa-eye").addClass("fa-eye-slash");
        } else {
            passwordField.attr("type", "password");
            $(this).removeClass("fa-eye-slash").addClass("fa-eye");
        }
    });
}

function changeOutgoingServerService() {
    $.get($("#GetMailDataUrl").val() + "?service=" + $("#OutServerService").val() + "&forCompany=true", function (response) {
        if (response.Error) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: response.Error,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
            return;
        }

        inputValueChanged = false;
        outServerDisplayServiceData();
        $("#OutServerCurrentService").val($("#OutServerService").val());
        $("#OutServerClassName").val(response.ClassName);
        $("#OutServerPort").val(response.Port ? response.Port : 0);
        $("#OutServer").val(response.Server ? response.Server : "");
        $("#OutServerEmailUsername").val(response.EmailUsername ? response.EmailUsername : "");
        $("#OutServerEmailPassword").val(response.EmailPassword ? response.EmailPassword : "");
        $("#OutServerTimeout").val(response.Timeout ? response.Timeout / 1000 : 30);
        if (($("#OutServerUseSASL").is(":checked") && response.UseSASL === false) || (!$("#OutServerUseSASL").is(":checked") && response.UseSASL === true))
            $("#OutServerUseSASL").click();
        if (($("#OutServerForceTLS12").is(":checked") && response.ForceTLS12 === false) || (!$("#OutServerForceTLS12").is(":checked") && response.ForceTLS12 === true))
            $("#OutServerForceTLS12").click();
        if (($("#OutServerUseEHLO").is(":checked") && response.UseEHLO === false) || (!$("#OutServerUseEHLO").is(":checked") && response.UseEHLO === true))
            $("#OutServerUseEHLO").click();
        $("#OutServerUseSMTPSend").val(response.UseSMTPSend);
        $("#OutServerUsePOP3Login").val(response.UsePOP3Login);
        $("#OutServerOutBox").val(response.OutBox);
        $("#OutServerInBox").val(response.InBox);
        $("#OutServerSender").val(response.Sender);
        $("#OutServerSenderName").val(response.SenderName);
        if ($("#OutServerService option:selected").val() === "smtp") {
            $('#OutServerUseSSLTLS option[value="' + response.UseSSLTLS + '"]').prop('selected', true);
        } else {
            $("#OutServerUseTLS").prop("checked", response.UseTLS);
            $('#OutServerUseSSLTLS').val("");
        }
    });
}

function saveAndTestConnection() {
    $("#testConnectionBtn i").addClass("fa-spin fa-spinner").removeClass("fa-check");
    saveCompanyData("true");
}

function testOutServerConnection() {
    $.get($("#TestConnectionUrl").val() + "?service=" + $("#OutServerService").val() + "&forCompany=true", function (response) {
        $("#testConnectionBtn i").removeClass("fa-spin fa-spinner").addClass("fa-check");
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: response.Error ? response.Error : response.Message,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }).fail(function () {
        $("#testConnectionBtn i").removeClass("fa-spin fa-spinner").addClass("fa-check");
    });
}

function outServerDisplayServiceData() {
    if ($("#OutServerService").val() === "smtp") {
        $("#defaultPort").text("(" + $("#DefaultLoc").val() + " 25)");
        $("#OutServerSmtpTLSorSSLContainer").attr("hidden", false);
        $("#OutServerOtherTLSorSSLContainer").attr("hidden", true);
    } else if ($("#OutServerService").val() === "imap") {
        $("#defaultPort").text("(" + $("#DefaultLoc").val() + " 993)");
        $("#OutServerSmtpTLSorSSLContainer").attr("hidden", true);
        $("#OutServerOtherTLSorSSLContainer").attr("hidden", false);
    }
}

function checkComplexity() {
    let password = $('.custom-modal #password-check-input').val();

    $.ajax({
        cache: false,
        type: "GET",
        url: $('#CheckPasswordEntropy').val(),
        data: {
            password: password
        },
        success: function (result) {
            passwordEntropy = Math.floor(result);

            $(".custom-modal #complexity-progressbar").removeClass();
            $(".custom-modal #password-message").show();

            if (passwordEntropy < 50) {
                $(".custom-modal #complexity-progressbar").addClass("easy");
                $(".custom-modal #password-strength").text($('#EasyLoc').val());
            }
            else if (passwordEntropy >= 50 && passwordEntropy < 100) {
                $(".custom-modal #complexity-progressbar").addClass("medium");
                $(".custom-modal #password-strength").text($('#MediumLoc').val());
            } else {
                $(".custom-modal #complexity-progressbar").addClass("demanding");
                $(".custom-modal #password-strength").text($('#DemandingLoc').val());
            }
        },
        error: function (error) {
            console.error(error)
        }
    });
}

function useComplexity() {
    if (passwordEntropy > 0) {
        var passwordLength = $(".custom-modal #password-check-input").val().length;
        $('#password-length-input').val(passwordLength);

        setComplexity(passwordEntropy);
    }
}

function setComplexity(value) {
    $.ajax({
        cache: false,
        type: "POST",
        url: $('#UpdatePasswordEntropy').val(),
        data: {
            passwordEntropy: value
        },
        success: function (result) {
            if (result.Success) {
                $('#password-entropy-value').val(value);
                $('.custom-modal #password-check-entropy').val(value);

                $('#easy').removeClass('active');
                $('#medium').removeClass('active');
                $('#demanding').removeClass('active');

                if (value < 50) {
                    $('#easy').addClass('active');
                }
                else if (value >= 50 && value < 100) {
                    $('#medium').addClass('active');
                } else {
                    $('#demanding').addClass('active');
                }

                saveCompanyData();
            }
        },
        error: function (error) {
            console.error(error)
        }
    });
}

function saveAndContactSupport() {
    saveCompanyData(false, true);
    paw.mod.Aion.fetchEncParameter().then(function (enc) {
        var href = $('#SupportUrl').val();
        href += '?ENC = ' + enc;
        window.open(href, '_blank');
    });
    
}