<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Project.Master" Inherits="System.Web.Mvc.ViewPage<AdministratorConsole.Models.ProjectController.IndexViewModel>" %>

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
    <% Html.DevExpress().RenderScripts(Page, new Script { ExtensionSuite = ExtensionSuite.GridView }); %>
    <% Html.DevExpress().RenderStyleSheets(Page, new StyleSheet { ExtensionSuite = ExtensionSuite.GridView }); %>

    <script language="javascript" type="text/javascript">

        var projectIds = [];
        var action = '';

        $(document).ready(function () {
            projectIds = [];
            updateModalContent();
        });

        function selectTaggedProjects(tagHTML, tag) {
            $(".project-tag").removeClass("selected");

            if ($(tagHTML).attr("id") != "all-tags") $(tagHTML).addClass("selected");

            $("#project-list-container").hide();
            $("#loading-projects").show();

            $.ajax({
                url: '<%= Url.Action("UpdateTaggedProjectList", "Project")%>',
                data: { tag: tag },
                type: "GET",
                cache: false,
                success: function (response) {
                    $("#project-list-container").html(response);

                    $("#loading-projects").hide();
                    $("#project-list-container").show();
                }
            });
        }

        function manageTags() {
            $.ajax({
                url: '<%= Url.Action("GetManageTags", "Tags")%>',
                type: "GET",
                success: function (response) {
                    $("#modal-overlay").html(response);
                },
                cache: false,
                complete: function () {
                    showModelDialog();
                }
            });
        }

        function customCommand(s, e) {
            var value = s.GetRowKey(e.visibleIndex);

            if (e.buttonID.toLowerCase() == 'openproject') {
                window.location = "<%= Url.Action("/Main/View/") %>" + value;
            }
        }

        function refreshPage() {
            window.location.href = '<%= Url.Action("List", "Project") %>';
        }

        window.onunload = function () {
            var cookie = getCookieValue("ClarityProjectsView");

            if (typeof (cookie) !== 'undefined') {
                var date = new Date();
                date.setTime(date.getTime() + (10 * 60 * 1000));

                ASPxClientUtils.SetCookie("ClarityProjectsView", cookie, date);
            }
        }

        function selecteProjectChanged(values) {
            projectIds = values;
            console.log(`projectIds: ${JSON.stringify(projectIds)}`);
            changeFieldsetStatus(values.length);
        }

        function changeFieldsetStatus(selectedProjects = 0) {
            console.log(`selectedProjects ${selectedProjects}`);
            if (selectedProjects > 0) {
                $("#btnDeactivate").prop('disabled', false);
                $("#btnDeactivate").prop('class', 'button');
                $("#btnDelete").prop('class', 'button');
                $("#btnDelete").prop('disabled', false);
            } else {
                $("#btnDeactivate").prop('disabled', true);
                $("#btnDeactivate").prop('class', 'button-disabled');
                $("#btnDelete").prop('class', 'button-disabled');
                $("#btnDelete").prop('disabled', true);
            }
        }

        function executeOperation() {
            console.log(`executeOperation operation: ${action} and projectIds: ${JSON.stringify(projectIds)}`);
            $("#btnDeactivate").prop('class', 'button-disabled');
            $("#btnDelete").prop('class', 'button-disabled');
            $("#spinner").prop('class', 'spinner-border spinner-border');
            let actionUrl = '';
            if (action === 'delete') {
                actionUrl = '<%= Url.Action("DeleteProjectIds", "Project") %>';
            } else if (action === 'deactivate') {
                actionUrl = '<%= Url.Action("DeactivateProjectIds", "Project") %>';
            }

            $.ajax({
                type: "POST",
                url: actionUrl,
                data: {
                    projectIds: projectIds
                },
                success: function (response) {
                    console.log('success');
                },
                complete: function () {
                    console.log('complete');
                    $("#btnDeactivate").prop('class', 'button');
                    $("#btnDelete").prop('class', 'button');
                    $("#spinner").prop('class', 'spinner-border spinner-border visually-hidden');
                    location.reload();
                }
            });
        }

        function updateModalContent() {
            const componentModal = document.getElementById('confirmationBatchOperationModal');
            if (componentModal) {
                componentModal.addEventListener('show.bs.modal', function (event) {
                    const button = event.relatedTarget;
                    action = button.getAttribute('data-bs-action');
                    const modalBody = componentModal.querySelector('.modal-body p');
                    let textBody = 'Do you confirm deleting the selected projects?';
                    if (action === 'deactivate') {
                        textBody = 'Do you confirm deactivating the selected projects?';
                    }

                    modalBody.textContent = textBody;
                });
            }
        }

    </script>

    <div id="content-wrap">
        <% Html.RenderPartial("Navigation/_SideNavigation", Model.MenuNavigationModel); %>
        <div id="content">
            <div class="row">
                <div class="col">
                    <h1 style="margin: 0px !important"><%= TextHelper.GetText("Projects") %></h1>
                </div>
                <div id="project-display-container" class="col d-flex gap-2 justify-content-end">
                    <a href="<%= Url.Action("Index", "Project") %>">
                        <img src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/Icons/card-display.png" title="Card View" alt="card view" class="project-display-select" />
                    </a>
                    <a href="<%= Url.Action("List", "Project") %>">
                        <img src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/Icons/list-display.png" title="List View" alt="list view" class="project-display-select" />
                    </a>
                    <% if ((Model.ClarityUser.IsAdministrator) || ((Model.ClarityUser.IsProjectCoordinator) && (Model.CanCoordinatorsCanProjects())))
                        { %>
                    <a href="<%= Url.Action("Deactivated", "Project") %>">
                        <img src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/Icons/deactivated-display.png" title="Show De-activated Projects" alt="show deactivated projects" class="project-display-select" />
                    </a>
                    <% } %>
                </div>
            </div>
            <% if (!Model.IsDefaultView("List"))
                { %>
            <div class="d-flex justify-content-end">
                <a href="<%= Url.Action("SetDefaultView", "Project", new { view = "list" }) %>">Set this as my default project view</a>
            </div>
            <% } %>

            <% if (Model.ClarityUser.IsAdministrator || (Model.ClarityUser.IsProjectCoordinator && Model.CanCoordinatorsCanProjects()))
                { %>
            <div class="row d-grip gap-2 d-md-flex justify-content-end">
                <button type="button" onclick="window.location.href='<%= Url.Action("Add", "Project") %>';" class="button" style="margin-top: 25px; height: 34px !important; width: 140px !important"><%= TextHelper.GetText("Add Project") %></button>
                <button type="button" id="btnDeactivate" disabled class="button-disabled" data-bs-toggle="modal" data-bs-target="#confirmationBatchOperationModal" data-bs-action="deactivate" style="margin-top: 25px; width: 105px !important">
                    <span id="spinner" class="spinner-border spinner-border visually-hidden" aria-hidden="true"></span>
                    <span role="status">Deactivate</span>
                </button>
                <button type="button" id="btnDelete" disabled class="button-disabled" data-bs-toggle="modal" data-bs-target="#confirmationBatchOperationModal" data-bs-action="delete" style="margin-top: 25px; width: 105px !important">
                    <span id="spinnerDelete" class="spinner-border spinner-border visually-hidden" aria-hidden="true"></span>
                    <span role="status">Delete</span>
                </button>
            </div>
            <% } %>

            <% if (Model.Projects.Count > 0)
                { %>
            <% if (!String.IsNullOrEmpty(Model.AllProjectsMessage))
                { %>
            <div><%= Html.Raw(Model.AllProjectsMessage) %></div>
            <br />
            <% } %>
            <form action="this">
                <div id="project-list-container" class="group">
                    <% Html.RenderPartial("Partials/ProjectList", Model.GetProjectCardsPartialViewModel()); %>
                </div>
            </form>
            <div id="loading-projects" style="display: none">
                <img src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/loading.gif" alt="loading" />
            </div>

            <!-- Modal -->
            <div class="modal fade" id="confirmationBatchOperationModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <div style="font-size: 20px; font-weight: 500;" id="staticBackdropLabel">Confirmation</div>
                        </div>
                        <div class="modal-body">
                            <p>Do you confirm to peform the selected operation?</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="button" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="button" data-bs-dismiss="modal" onclick="executeOperation()">Accept</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--End of Modal -->

            <% }
                else
                { %>
            <% if (Model.ClarityUser.IsAdministrator)
                { %><%= TextHelper.GetText("No projects exist. To create a project, click \"Add Project\".")%>
            <% }
                else
                { %><%= TextHelper.GetText("Not assigned to any projects, contact your admin to be able to get access to the projects")%>
            <% } %>
            <% } %>
        </div>
    </div>
</asp:Content>
