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

<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() == "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", "ProjectTasks") %>',
                type: "GET",
                data: {
                    "projectId": "<%= Model.CurrentProject.ExternalId %>"
                },
                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", "ProjectTasks") %>',
                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="banner-space">
        <div id="banner-detail-container">
            <div class="left-floating-panel">
	            <div id="project-title"><span><%= Html.Encode(Model.CurrentProject.Name) %></span><span id="project-number"><%= Html.Encode(Model.CurrentProject.Number) %></span></div>
                <div id="project-database-export"><b>Last Database Export:</b> <% if (Model.CurrentProject.LastDatabaseExport != null) { %><%= DateTimeHelper.ToString(Model.CurrentProject.LastDatabaseExport.Value) %><% } else { %>No Exports<% } %></div>
	        </div>
            <% if (Model.LicenseType != LicenseType.ODP)
               { %>
                <div class="right-floating-panel total-time-container-outer">
                    <div id="total-time-container">
				        <div class="header">Total Time Saved</div>
			            <div class="value"><%= (Math.Ceiling(Model.CurrentProject.CompletedTasksTime.TotalHours)).ToString("000") %> hrs</div>
                    </div>
                </div> 
            <% } %>
            <% Html.RenderPartial("Partials/LaunchableTasks", new LaunchableTasksModel(Model.CurrentProject, Model.TaskSchedules, Model.CurrentUser)); %>
            <div class="clear"></div>
        </div>
    </div>
    <div id="content-wrap">
        <% Html.RenderPartial("Navigation/_SideNavigation", Model.MenuNavigationModel); %>
	    <div id="content">
	        <h1 class="left-floating-panel">Tasks</h1>
            <div class="right-floating-panel">Server Timezone<br /><b><%= DateTimeHelper.GetTimezoneName() %></b></div>
            <div class="clear"></div>
            <div id="tab-container">
                <ul class="tabs">
			        <li><a href="<%= Url.Action("TaskDashboard/" + Model.CurrentProject.ExternalId, "ProjectTasks") %>">Dashboard</a></li>
			        <li><a href="<%= Url.Action("CurrentTasks/" + Model.CurrentProject.ExternalId, "ProjectTasks") %>" class="active">Current Tasks</a></li>
			        <li><a href="<%= Url.Action("CompletedTasks/" + Model.CurrentProject.ExternalId, "ProjectTasks") %>">Completed Tasks</a></li>
                    <% if ((Model.CurrentProject.HasAdministratorAccess(Model.CurrentUser)) || (Model.CurrentProject.HasTaskCoordinatorAccess(Model.CurrentUser)))
                        { %>
                            <li><a href="<%= Url.Action("TaskSchedules/" + Model.CurrentProject.ExternalId, "ProjectTasks") %>">Setup Tasks</a></li>
                    <% } %>
                    <% if (Model.CurrentProject.HasAdministratorAccess(Model.CurrentUser))
                        { %>
                            <li><a href="<%= Url.Action("Authorization/" + Model.CurrentProject.ExternalId,"ProjectTasks") %>">Authorization</a></li>
			                <li><a href="<%= Url.Action("TaskServers/" + Model.CurrentProject.ExternalId,"ProjectTasks") %>">Task Servers</a></li>
                    <% } %>
			        <li><a href="<%= Url.Action("TaskTimelineOverview/" + Model.CurrentProject.ExternalId, "ProjectTasks") %>" >Timeline</a></li>
			        <li><a href="<%= Url.Action("TaskTimeline/" + Model.CurrentProject.ExternalId, "ProjectTasks") %>" class="line-height-24">Timeline <br /> Detailed</a></li>
                    <% if (Model.CurrentProject.UserHasTaskAccess(Model.CurrentUser))
                        { %>
                            <li><a href="<%= Url.Action("CommonTaskTargets/"+ Model.CurrentProject.ExternalId, "ProjectTasks" ) %>" class="line-height-24">Task <br /> Targets</a></li>
                            <li><a href="<%= Url.Action("MetadataMapping/"+ Model.CurrentProject.ExternalId, "Project" )%>" class="line-height-24" >Metadata <br /> Mapping</a></li>
                    <% } %>
                </ul>
	        </div>
            <br />
            <% if (Model.CurrentTasks.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.GetCurrentTasksPartialViewModel()); %></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='<%= Url.Action("CurrentTasks/" + Model.CurrentProject.ExternalId, "ProjectTasks") %>'" 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("ClarityCurrentProjectTasksView");
        
            if (typeof (cookie) !== 'undefined') {
                var date = new Date();
                date.setTime(date.getTime() + (10 * 60 * 1000 * 52560));

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