@model PantheonRA.BackOffice.Models.MailboxViewModel
@using PantheonRA.BackOffice.Models
@using PantheonRA.WebApi.Contracts.Enums
@using PAW.Contracts.Enums;
@{
    ViewBag.Title = Loc.MailboxBasicData;
}

<div class="tabs-container">
    @Html.Partial("~/Views/Company/_CompanySettingsTabNavigation.cshtml")
    <div class="tab-content">
        <form id="mainForm" method="post">
            @Html.HiddenFor(model => model.AnQid)
            @Html.HiddenFor(model => model.LoginsQid)

            <div class="row buttons-tabbed">
                @Html.Partial("_FormButtons", new FormButtonsViewModel
                {
                    BackUrl = Url.Action("Index", "Settings"),
                    SaveButtonGroup = new FormButtonGroup
                    {
                        Buttons = new List<FormButton>
                        {
                            new FormButton { Text = Loc.Save, Icon = "fa fa-save fa-lg", IsSubmit = true }
                        }
                    }
                })
            </div>
            <div class="divided-content clearfix">
                <div class="divided-content-main divided-content-full">
                    <div class="form-horizontal form-md row">
                        <div class="col-sm-6 col-lg-5">
                            <h3 class="m-b-md m-t-md">@Loc.MailboxBasicData</h3>
                            <div class="form-group">
                                @Html.LabelFor(model => model.Name, Loc.Name, new { @class = "col-md-3 control-label" })
                                <div class="col-md-9">
                                    @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                                </div>
                            </div>

                            <div class="form-group">
                                @Html.LabelFor(model => model.ClassificationQid, Loc.Classification, new { @class = "col-md-3 control-label" })
                                <div class="col-md-9">
                                    @Html.HiddenFor(model => model.ClassificationQid)
                                    @Html.TextBoxFor(model => model.ClassificationName,
                                        HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_wide form-input-required", "ClassificationName", false, Loc.Classification))
                                </div>
                            </div>

                            <div class="form-group">
                                @Html.LabelFor(model => model.Subject, Loc.Subject, new { @class = "col-md-3 control-label" })
                                <div class="col-md-9">
                                    @Html.HiddenFor(model => model.Subject)
                                    <input type="text" value="@Model.Subject" id="SubjectView" class="form-control typeahead_3 typeahead_wide form-input-required" autocomplete="off" />
                                </div>
                            </div>

                            <div class="form-group">
                                @Html.LabelFor(model => model.LoginsQid, Loc.Login, new { @class = "col-md-3 control-label" })
                                <div class="col-md-9">
                                    <div class="input-group">
                                        <input disabled class="form-control" id="LoginName" value="@Model.LoginName" title="@Model.LoginName" autocomplete="off" onclick="$(this).closest('.input-group').find('button').trigger('click'); $(this).blur();" />
                                        @Html.HiddenFor(model => model.LoginsQid)
                                        <span class="input-group-addon">
                                            <button type="button" class="btn btn-ghost btn-xs padding-bottom-none" onclick="openLoginsModal();" title="@Loc.OpenLogin">
                                                <i class="fas fa-pencil-alt"></i>
                                            </button>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

@section pageScripts{
    @Scripts.Render("~/bundles/admin")
    <script>
        $(document).ready(function () {
            initializeClassificationTypeahead('@Url.Action("SearchClassifications", "Documents")', $('#ClassificationName'), $('#ClassificationQid'));
            initializePartnerTypeahead('@Url.Action("SearchPartners", "Company")', $('#SubjectView'), $('#Subject'));
            prepareMailboxLoginsModal(@Html.Raw(Json.Encode(ViewBag.Logins)), '@Loc.Login', ['@Loc.Default', '@Loc.User', '@Loc.UserName', '@Loc.Password']);
        });

        function openLoginsModal() {
            $("#mailboxLoginsModal").customModal("open");
        }

        function generateMailboxLoginRow(anQid, isDefault, userName, anUserId, acUserId, password, buttonIcon, onbuttonClick, disableIsDefault) {
            return "<tr data-qid='" + anQid + "'><td class='no-padding centered'><input type='checkbox' onChange='onIsDefaultChange(this)' class='form-control custom-checkbox mailboxIsDefault' " + (isDefault ? "checked" : "") + " " + (disableIsDefault ? "disabled" : "") + " /></td><td class='no-padding'><input class='mailboxAnUserId' type='hidden' onChange='mailboxChange(this)' value='" + anUserId + "' /><input class='form-control typeahead_3 mailboxAcUserId' value='" + (acUserId ? acUserId : "") + "' autocomplete='off' /></td><td class='no-padding'><input class='form-control mailboxAcUserName' onBlur='mailboxChange(this)' value='" + (userName ? userName : "") + "' /></td><td class='no-padding'><input type='password' class='form-control mailboxPassword' onBlur='mailboxChange(this)' value='" + password + "' /></td><td><button class='btn btn-ghost btn-ghost-default' onClick='" + onbuttonClick + "'><i class='" + buttonIcon + "'></i></button></td></tr>";
        }

        function prepareMailboxLoginsModal(data, title, tableTitles, onSave, onClose) {
            let addLine = "<tr><td class='no-padding centered'><input type='checkbox' class='form-control custom-checkbox' disabled /></td><td class='no-padding'><input class='mailboxAnUserId' type='hidden' /><input class='form-control typeahead_3 mailboxAcUserId' placeholder='" + tableTitles[2] + "' /></td><td class='no-padding'><input class='form-control mailboxAcUserName' placeholder='" + tableTitles[1] + "' /></td><td class='no-padding'><input class='form-control mailboxPassword' placeholder='" + tableTitles[3] + "' /></td><td><button class='btn btn-primary' onClick='addMailboxLogin(this)'><i class='fa fa-plus'></i></button></td></tr>";
            let rowLines = "";

            if (data) {
                for (var a = 0; a < data.length; a++) {
                    rowLines += generateMailboxLoginRow(data[a].AnQid, data[a].IsDefault, data[a].UserName, data[a].AnUserId, data[a].AcUserId, "Password", "fa fa-trash-alt", "onDeleteMailboxLogin(this)");
                }
            }

            $().customModal({
                destroyOnClose: false,
                showCloseButton: true,
                type: "modal",
                id: "mailboxLoginsModal",
                help: '@SiteHelpAttributeHelper.GetHelpUrl(PantheonRA.BackOffice.Enums.HelpIds.Mailboxes)',
                title: title,
                openOnCreate: false,
                onCreated: function () {
                    $("#mailboxLoginsModal .custom-checkbox").customCheckbox();
                    $("#mailboxLoginsModal .typeahead_3").each(function () {
                        let $element = $(this);
                        initializeUserTypeahead('@Url.Action("SearchUsers", "Task")', $(this), $(this).prev(), function () { $element.prev().trigger("change"); });
                    });
                },
                content: "<table class='table table-bordered add-modal-table'><thead><tr><th width='10%'>" + tableTitles[0] + "</th><th width='30%'>" + tableTitles[1] + "</th><th width='25%'>" + tableTitles[2] + "</th><th>" + tableTitles[3] + "</th><th width='33px'></th></tr></thead><tbody>" + addLine + rowLines + "<tbody></table>",
                buttons: [
                    {
                        text: '@Loc.Save',
                        icon: 'fa fa-save',
                        type: 'primary',
                        closeOnAction: true
                    }
                ]
            });
        }

        async function addMailboxLogin(element) {
            $(element).attr("disabled", true);
            $(element).find("i").removeClass("fa-add").addClass("fa-spinner fa-spin");

            let $selectedRow = $(element).closest("tr");
            let newMailboxLogin = {
                UserName: $selectedRow.find(".mailboxAcUserName").val(),
                AnUserId: $selectedRow.find(".mailboxAnUserId").val(),
                AcUserId: $selectedRow.find(".mailboxAcUserId").val(),
                Password: $selectedRow.find(".mailboxPassword").val()
            };
            await fetch('@Url.Action("AddMailboxLogin", "Mailbox")', {
                method: "POST",
                body: JSON.stringify(newMailboxLogin),
                headers: { 'Content-Type': 'application/json' },
            }).then((response) => response.json()
            ).then(async (response) => {
                if (!response) throw ('@Loc.GeneralError');

                newMailboxLogin.AnQid = response;

                let newMailboxLoginRow = generateMailboxLoginRow(newMailboxLogin.AnQid, false, newMailboxLogin.UserName, newMailboxLogin.AnUserId,
                    newMailboxLogin.AcUserId, "Password", "fa fa-trash-alt", "onDeleteMailboxLogin(this)");
                let $newMailboxLoginRow = $(newMailboxLoginRow);
                $selectedRow.closest("table").append($newMailboxLoginRow);

                $newMailboxLoginRow.find(".custom-checkbox").customCheckbox();
                $newMailboxLoginRow.find(".typeahead_3").each(function () {
                    let $element = $(this);
                    initializeUserTypeahead('@Url.Action("SearchUsers", "Task")', $(this), $(this).prev(), function () { $element.prev().trigger("change"); });
                });

                $selectedRow.find("input").val("");
            }).catch((error) => {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    closeOtherModals: false,
                    type: "error",
                    text: error,
                    buttons: [{
                        text: '@Loc.OK',
                        icon: 'fa fa-check',
                        type: 'primary',
                        closeOnAction: true
                    }]
                });
            });

            $(element).find("i").addClass("fa-add").removeClass("fa-spinner fa-spin");
            $(element).removeAttr("disabled");
        }

        function onDeleteMailboxLogin(element) {
            $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    closeOtherModals: false,
                    type: "question",
                    text: "@Loc.ConfirmDeleteMessage",
                    buttons: [{
                        text: '@Loc.OK',
                        icon: 'fa fa-check',
                        type: 'primary',
                        closeOnAction: true,
                        action: async function () {
                            await deleteMailboxLogin(element);
                        }}, {
                        text: '@Loc.Cancel',
                        icon: 'fa fa-times',
                        type: 'defailt',
                        closeOnAction: true
                    }]
                });
        }

        async function deleteMailboxLogin(element) {
            let $selectedRow = $(element).closest("tr");

            $(element).attr("disabled", true);
            $(element).find("i").removeClass("fa-trash-alt").addClass("fa-spinner fa-spin");

            await fetch('@Url.Action("DeleteMailboxLogin", "Mailbox")', {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ anQid: $selectedRow.attr("data-qid") })
            }).then((response) => response.json()
            ).then(async (response) => {
                if (!response) throw ('@Loc.GeneralError');
                $selectedRow.remove();
            }).catch((error) => {
                $(element).find("i").addClass("fa-trash-alt").removeClass("fa-spinner fa-spin");
                $(element).removeAttr("disabled");

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    closeOtherModals: false,
                    type: "error",
                    text: error,
                    buttons: [{
                        text: '@Loc.OK',
                        icon: 'fa fa-check',
                        type: 'primary',
                        closeOnAction: true
                    }]
                });
            });
        }

        async function onIsDefaultChange(element) {
            let $selectedRow = $(element).closest("tr");
            let loginId = null;
            if ($(element).is(":checked")) loginId = $selectedRow.attr("data-qid");

            $(element).closest("table").find("input[type='checkbox']").attr("disabled", true);
            let $loader = $("<i class='fa fa-spinner fa-spin'></i>");
            $(element).closest("td").append($loader);
            $(element).parent().hide();

            await fetch('@Url.Action("SetDefaultMailboxLogin", "Mailbox")?mailboxId=@Model.AnQid&loginId=' + loginId, {
                method: "GET",
                headers: { 'Content-Type': 'application/json' },
            }).then((response) => response.json()
            ).then(async (response) => {
                if (!response) throw ('@Loc.GeneralError');
                $(element).closest("table").find("input[type='checkbox']").prop("checked", false);
                $(element).prop("checked", loginId == null ? false : true);
                $("#LoginsQid").val(loginId == null ? "" : loginId);
                $("#LoginName").val(loginId == null ? "" : $(element).closest("tr").find(".mailboxAcUserName").val());
            }).catch((error) => {
                $(element).prop("checked", !$(element).is(":checked"));

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    closeOtherModals: false,
                    type: "error",
                    text: error,
                    buttons: [{
                        text: '@Loc.OK',
                        icon: 'fa fa-check',
                        type: 'primary',
                        closeOnAction: true
                    }]
                });
            });

            $loader.remove();
            $(element).closest("table tbody").find("tr:not(:first)").find("input[type='checkbox']").removeAttr("disabled");
            $(element).parent().show();
        }

        async function mailboxChange(element) {
            let $selectedRow = $(element).closest("tr");

            $selectedRow.find("input, button").attr("disabled", true);
            $selectedRow.find("i").removeClass("fa-trash-alt").addClass("fa-spinner fa-spin");

            let mailboxLogin = {
                AnQid: $selectedRow.attr("data-qid"),
                UserName: $selectedRow.find(".mailboxAcUserName").val(),
                AnUserId: $selectedRow.find(".mailboxAnUserId").val(),
                AcUserId: $selectedRow.find(".mailboxAcUserId").val(),
                Password: $selectedRow.find(".mailboxPassword").val()
            };
            await fetch('@Url.Action("UpdateMailboxLogin", "Mailbox")', {
                method: "POST",
                body: JSON.stringify(mailboxLogin),
                headers: { 'Content-Type': 'application/json' },
            }).then((response) => response.json()
            ).then(async (response) => {
                if (!response) throw ('@Loc.GeneralError');
            }).catch((error) => {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    closeOtherModals: false,
                    type: "error",
                    text: error,
                    buttons: [{
                        text: '@Loc.OK',
                        icon: 'fa fa-check',
                        type: 'primary',
                        closeOnAction: true
                    }]
                });
            });

            $selectedRow.find("i").addClass("fa-trash-alt").removeClass("fa-spinner fa-spin");
            $selectedRow.find("input, button").removeAttr("disabled");
        }
    </script>
}