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

<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.NavigationAndLayout },
            new StyleSheet { ExtensionSuite = ExtensionSuite.Editors },
            new StyleSheet { ExtensionSuite = ExtensionSuite.HtmlEditor },
            new StyleSheet { ExtensionSuite = ExtensionSuite.GridView }
     ); %>
     <script language="javascript" type="text/javascript">
         var baseUrl = "";

         window.onload = function () {
             baseUrl = document.getElementById("HiddenCurrentUrl").value;
             baseUrl = baseUrl.substring(0, baseUrl.indexOf("Dummy"));
         };

         function CustomButtonClicked(s, e) {
             e.processOnServer = false;

             var value = s.GetRowKey(e.visibleIndex);

             
             if (e.buttonID.toLowerCase() == "prioritizebutton") {
                 document.location = baseUrl + "PrioritizeTask/" + value;
             }
             else if (e.buttonID.toLowerCase() == "deletebutton") {
                getAffectedTasks(value, function (tasks) {
                    if (tasks && tasks.length > 1) {
                        var taskList = document.createElement("div");
                        taskList.style.listStyleType = "none";
                        taskList.style.paddingLeft = "20px";
                        const textNode = document.createElement("div");
                        textNode.innerText = "Deleting this task will terminate the following tasks. Do you want to continue?";
                        taskList.appendChild(textNode);
                        tasks.forEach(task => {
                            const listItem = document.createElement("li");
                            listItem.textContent = `${task.Id}: ${task.Name}`;
                            taskList.appendChild(listItem);
                        });
                        displayConfirmElement('confirm-delete-claimed', 'Terminate Tasks?', taskList, function () {
                            document.location = baseUrl + "DeleteTask/" + value;
                        });
                    }
                    else
                        document.location = baseUrl + "DeleteTask/" + value;
                });
             }
         }

         function getAffectedTasks(id, callback) {
             var selectedFiles = [];
             $.ajax({
                url: '<%= Url.Action("GetAffectedTasksByTermination", "Task") %>',
                type: "GET",
                data: {
                    id: id
                },
                cache: false,
                success: function (result) {
                    callback(result);
                },
                error: function (response) {
                    callback(null);
                }
            });
          }

         $(document).ready(function () {
             $("#btShowCustomizationWindow").click(function () {
                 UpdateCustomizationWindowVisibility();
             });
         });

         function grid_CustomizationWindowCloseUp(s, e) { }

         function UpdateCustomizationWindowVisibility() {
             if (gvDataBinding.IsCustomizationWindowVisible()) gvDataBinding.HideCustomizationWindow();
             else gvDataBinding.ShowCustomizationWindow();
         }

         function DisableCustomizationWindow() {
             if (gvDataBinding.IsCustomizationWindowVisible()) gvDataBinding.HideCustomizationWindow();
         }

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

         

        <% if (TempData["KillTaskSent"] != null) { %>

         function isTaskKilled() {
             var selectedFiles = [];
             $.ajax({
                 url: '<%= Url.Action("IsTaskKillProcessed", "Task") %>',
                type: "GET",
                data: {
                     id: <%= TempData["KillTaskSent"] %>
                },
                 cache: false,
                 success: function (result) {
                     if (result.Processed) {
                         $("#pending-killtask-confirmation").fadeOut("fast", function () {
                             $("#success-killtask-confirmation").fadeIn("fast");
                             clearInterval(refreshIntervalId);
                         });
                     }
                     else if (timeWaitingForResponse > 60000) {
                         $("#pending-killtask-confirmation").fadeOut("fast", function () {
                             $("#failed-killtask-confirmation").fadeIn("fast");
                             clearInterval(refreshIntervalId);
                         });
                     }
                 },
                 error: function (response) {
                     $("#pending-killtask-confirmation").fadeOut("fast", function () {
                         $("#failed-killtask-confirmation").fadeIn("fast");
                         clearInterval(refreshIntervalId);
                     });
                 }
             });
         }

         var interval = 5000;
         var timeWaitingForResponse = 0;
         var refreshIntervalId = setInterval(function () {
             isTaskKilled();
             timeWaitingForResponse += interval;
         }, interval);
        <% } %>


     </script>
    <div id="content-wrap">
        <% Html.RenderPartial("Navigation/_SideNavigation", Model.MenuNavigationModel); %>
        <div id="content">
		    <h1 class="left-floating-panel">Current Tasks</h1>
            <div class="right-floating-panel">Server Timezone<br /><b><%= DateTimeHelper.GetTimezoneName() %></b></div>
            <div class="clear"></div>
            <% if (Model.Tasks.Count > 0) { %>
                <div class="left-floating-panel"><input id="btShowCustomizationWindow" type="button" value="Column Select" class="button" /></div>
                <div class="clear"></div>
                <div id="GridViewContainer" class="reportPanel-scrollingbody" style="min-height:200px;"><% Html.RenderPartial("Partials/CurrentTasks", Model.Tasks); %></div>
                <div class="left-floating-panel"><input type="button" value="Delete All" onclick="deleteAllTasks()" class="button" /></div>
            <% } else  { %>
                <div>No Tasks Outstanding</div>
            <% } %>
            <div class="right-floating-panel"><input type="button" value="Refresh" onclick="window.location.href = '<%= Url.Action("Current", "Task") %>';" class="button" /></div>
            <div class="clear"></div>
        </div>
    </div>
     <% if (TempData["KillTaskSent"] != null) { %>
            <div id="killTaskLoadingContainer">
                <div id="pending-killtask-confirmation">
                    <img alt="loading indicator" src='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/loading.gif' class='img-loading' title='Loading' />
                    <br />
                    Waiting for Confirmation...
                </div>
                <div id="success-killtask-confirmation" style="display:none;">
                    <img alt="loading indicator" src='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/icon-completed-tasks.png' class='img-loading' title='Loading' />
                    <br />
                    Task deleted
                </div>
                <div id="failed-killtask-confirmation" style="display:none;">
                    <img alt="loading indicator" src='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/icon-warnings.png' class='img-loading' title='Loading' />
                    <br />
                    Unable to delete task.
                </div>
                <br />
                <div class="right-floating-panel"><input type="button" value="Close" class="button" onclick="RemoveDiv('killTaskLoadingContainer');" /></div>
                <div class="clear"></div>  
            </div> 
        <% } %>
    <script type="text/javascript">
        window.onunload = function () {
            var cookie = getCookieValue("ClarityCurrentTasksView");
           
            if (typeof (cookie) !== 'undefined') {
                var date = new Date();
                //expires next year
                date.setTime(date.getTime() + (10 * 60 * 1000 * 52560));

                ASPxClientUtils.SetCookie("ClarityCurrentTasksView", cookie, date);
            }
        }
    </script>
</asp:Content>
