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

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
    <% Html.DevExpress().RenderScripts(Page, new Script { ExtensionSuite = ExtensionSuite.Editors }); %>
    <% Html.DevExpress().RenderStyleSheets(Page, new StyleSheet { ExtensionSuite = ExtensionSuite.Editors } ); %>
    <link href='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Content/themes/base/jquery-ui.css' rel="stylesheet" type="text/css" />
    <link href='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery.multiselect/jquery.multiselect.css' rel="stylesheet" type="text/css" /> 
    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery.multiselect/jquery.multiselect.js" type="text/javascript"></script>
    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery-ui-1.14.0.min.js" type="text/javascript"></script>
    <% Html.RenderPartial("Task/TaskAutocompleteComboBox"); %>
    <% Html.RenderPartial("Task/TaskInputFunctions"); %>
    <% Html.RenderPartial("Task/TaskViewExpressionBuilder"); %>
        
    <script language="javascript" type="text/javascript">
        var taskSubmitted = false;

        $(document).ready(function () {
            initialize();
        });

        async function initialize() {
            const taskType = '<%=Model.TaskSchedule.TaskType.ToLower() %>';
            if (taskType && taskType === 'tasksequence') {
                $('#btn-update-and-run').prop('disabled', true);
                $('#btn-update').prop('disabled', true);
                await loadTaskSequence()
                $('#btn-update-and-run').prop('disabled', false);
                $('#btn-update').prop('disabled', false);
            }
        }

        async function loadTaskSequence() {
            const scope = '<%= Model.TaskSchedule.Scope %>';
            const taskScheduleId = '<%= Model.TaskSchedule.Id %>';
            const externalId = '<%= Model.CurrentProject.ExternalId %>';
            const response = await getTaskSequence('project', scope, taskScheduleId, externalId);
            $('#super-task-sequence').empty();
            $('#super-task-sequence').html(response);
        }
        
        function returnToMain() {
            clearWebTriggersessionStorage();
            window.location.href = "<%= Url.Action("TaskSchedules/" + Model.CurrentProject.ExternalId, "ProjectTasks") %>";
        }
        
        function submitForm(runNewSchedule) {
            <% if (Model.TaskTargetModelWarning.HasValue) { %>
                if ($("#Scope").val().toLowerCase() == "file") {
                    var target = $("#Target").val().trim();

                    if (target == "*") {
                        $.ajax({
                        type: 'POST',
                            url: '<%= Url.Action("LoadCountModelsIncluded", "Task") %>',
                            data: {
                                projectId: $("#ProjectId").val(),
                                searchTerm: target
                            },
                            cache: false,
                            success: function (response) {
                                var includedFiles = JSON.parse(response);

                                if (includedFiles.length > <%= Model.TaskTargetModelWarning %>) {
                                    $.ajax({
                                        type: 'GET',
                                        url: '<%= Url.Action("GetConfirmSubmitTaskDialog", "Task") %>',
                                        data: {
                                            includedFileCount: includedFiles.length,
                                            runNewSchedule: ((runNewSchedule != null) && (runNewSchedule))
                                        },
                                        cache: false,
                                        success: function (response) {
                                            $("#modal-overlay").html(response);
                                        },
                                        complete: function () {
                                            showModelDialog();
                                        }
                                    });
                                }
                                else submitTask(runNewSchedule);
                            }
                        });
                    }
                    else submitTask(runNewSchedule);
                }
                else submitTask(runNewSchedule);
            <% } else { %>
                submitTask(runNewSchedule);
            <% } %>
        }

        function submitTask(runNewSchedule) {
            $("#validation-error").empty();
            $("#validation-error").hide();
            
            var validationResults = [];
            
            if (!validateInputtedTaskParameters()) {
                validationResults.push("All the required task inputs were not provided");
            }

            if (!isValidMaxDays()) {
                validationResults.push("The schedule days are greater than the maximum allowed.");
            }

            <% if (!string.IsNullOrEmpty(Model.TaskSchedule.Validation)) { %>
                try {
                    var validate = <%= Model.TaskSchedule.Validation %>;

                    validationResults = validate();
                }
                catch(err) {
                    console.log("Error validating task: " + err.toString());
                }
            <% } %>
                
            if (validationResults.length > 0) {
                $("#validation-error").show();
                $("#validation-error").html(validationResults.join("<br/>"));

                return;
            }
            
            finalizePostAction();
            collectWebTriggerData();

            <% if (Model.TaskSchedule.TaskType.ToLower() == "tasksequence") { %>
                var scriptSequence = "";
                
                $(".sequence-script").each(function() {
                    if ($(this).attr("task-id")) scriptSequence += "," + $(this).attr("task-id");
                });

                if (scriptSequence .length > 0) scriptSequence = scriptSequence.substring(1);

                $("#TaskSequence").val(scriptSequence);
            <% } %>

            $(".taskScheduleOptionMultiselect").each(function (index, multiselect) {
                var value = "";
                $(multiselect).find('input').each(function (inputIndex, checkbox) {
                    if (checkbox.checked) {
                        value += $(checkbox).val() + "\n";
                    }
                });
                value = value.slice(0, -1);
                $("<input />").attr("type", "hidden")
                    .attr("name", multiselect.id)
                    .attr("value", value)
                    .appendTo("#CurrentTaskSchedule");
            });
            
            if (runNewSchedule) $('#CurrentTaskSchedule').attr('action', "<%= Url.Action("UpdateAndRunTaskSchedule/" + Model.TaskSchedule.Id, "ProjectTasks") %>");
                
            if (!taskSubmitted) {
                taskSubmitted = true;

                $("#CurrentTaskSchedule").submit();
            }
        }
    </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.HasValue) { %><%= 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), new ViewDataDictionary{ { "removeJqueryUI", "true" } }); %>
            <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") %>" >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") %>" class="active">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 />
            <% using (Html.BeginForm("UpdateTaskSchedule/" + Model.TaskSchedule.Id, "ProjectTasks", new { returnTo = Model.ReturnTo }, FormMethod.Post, new { @id = "CurrentTaskSchedule" }))
                { %>
                <div class="right-floating-panel"><input type="button" id="btn-update" value="Update" class="button" onclick="submitForm()" /></div>
                <div class="right-floating-panel"><input type="button" id="btn-update-and-run" value="Update and Run" class="button" onclick="submitForm(true)" /></div>
                <div class="right-floating-panel"><input type="button" value="Cancel" class="button" onclick="returnToMain()" /></div>
                <div><input type="hidden" id="WebTriggerData" name="WebTriggerData" /></div>
                <% if (Model.TaskTemplate != null) { %>
                    <div class="left-floating-panel">
                        <div class="table">
                            <div class="table-row">
                                <div class="table-cell"><h2 class="right-margin"><%= Html.Encode(Model.TaskSchedule.TaskTypeName)%></h2></div>
                                <div class="table-cell"><%= Html.ActionLink("(Linked to Task Template: " + Model.TaskTemplate.Name + ")", "Edit/" + Model.TaskTemplate.Id, "TaskTemplate", null, new { @target = "_blank" }) %></div>
                            </div>
                        </div>
                    </div>
                <% } else { %>
                    <div class="left-floating-panel"><h2><%= Html.Encode(Model.TaskSchedule.TaskTypeName)%></h2></div>
                <% } %>
                <div class="clear"></div>
                <br />
                <div class="right-floating-panel"><a href="<%= WebHelpHelper.GetWebHelpURL(((LicenseType)ViewData["LicenseType"])) %>index.htm#t=Admin_%26_Coordinators_Guide%2FProject_Setup%2FTasks%2FTasks_Setup.htm" target="_blank">Task Help</a></div>
                <div class="clear"></div>
                <% Html.RenderPartial("Task/EditTaskDetail", new EditTaskDetailViewModel(Model.TaskSchedule, Model.CurrentProject, Model.TaskScopeTypes, Model.TaskScheduleHours, Model.TaskScheduleMinutes, Model.PostActions, Model.DisabledPostTaskActions, Model.DefaultOnlyOnChange, Model.CurrentTaskSchedulePostTaskActionParameters, maxDaysForWeeklyScheduledTasks: Model.MaxDaysForWeeklyScheduledTasks)); %>
                <% if (Model.TaskSchedule.TaskType.ToLower() != "tasksequence")
                    { %>
                    <% if ((!String.IsNullOrEmpty(Model.TaskSchedule.HelpURL)) || (!String.IsNullOrEmpty(Model.TaskSchedule.ConfigHeader)))
                        { %>
                        <hr />
                    <% } %>
                    <div id="validation-error" class="validation-summary-error left-floating-panel" style="margin-bottom:15px;display:none;"></div>
                    <% if (!String.IsNullOrEmpty(Model.TaskSchedule.HelpURL))
                        { %>
                        <div class="right-floating-panel"><a href="<%= TaskHelper.GenerateTaskPluginHelpURL(((LicenseType)ViewData["LicenseType"]), Model.TaskSchedule.HelpURL) %>" target="_blank"><%= Html.Encode(Model.TaskSchedule.TaskTypeName)%> Help</a></div>
                    <% } %>
                    <div class="clear"></div>
                    <% if (!String.IsNullOrEmpty(Model.TaskSchedule.ConfigHeader))
                        { %>
                        <p><%= Html.Raw(Model.TaskSchedule.ConfigHeader) %></p>
                    <% } %>
                     <% if (AdministratorConsole.CustomTaskViewFactory.HasCustomView(Model.TaskSchedule.TaskType) && Model.TaskSchedule.TaskInputParameters != null  && Model.TaskSchedule.TaskInputParameters.Count > 0) { %>
                        <% Html.RenderPartial(AdministratorConsole.CustomTaskViewFactory.GetCustomView(Model.TaskSchedule.TaskType), AdministratorConsole.CustomTaskViewFactory.GetCustomViewModel(Model.TaskSchedule)); %>
                    <%} else if ((Model.TaskSchedule.TaskInputParameters != null) && (Model.TaskSchedule.TaskInputParameters.Count > 0))
                        { %>
                        <% for (int i = 0; i < Model.TaskSchedule.TaskInputParameters.Count; i++)
                            { %>
                            <% 
                                string parameterValue = Model.TaskSchedule.TaskInputParameters[i].ParameterDefault;
                                if (Model.TaskSchedule.GetTaskParameter(Model.TaskSchedule.TaskInputParameters[i].Name).Trim().Length > 0) parameterValue = Model.TaskSchedule.GetTaskParameter(Model.TaskSchedule.TaskInputParameters[i].Name);
                            %>
                            <% Html.RenderPartial("Task/TaskScheduleInputParameter", new AdministratorConsole.Models.Shared.TaskController.TaskScheduleInputParameterViewModel() {
                                    TaskScheduleInputParameter = Model.TaskSchedule.TaskInputParameters[i],
                                    TaskScheduleParameters = Model.TaskSchedule.TaskScheduleParameters.ToList(),
                                    ParameterValue = parameterValue
                                }); %>
                        <% } %>
                        <div class="clear"></div>
                    <% } %>
                <% }
                    else
                    { %>
                    <hr />
                    <div id="super-task-sequence"></div>
                <% } %>
                <hr />
                <table class="standard-list full">
                    <tr>
                        <td><b>Notes</b></td>
                    </tr>
                    <tr>
                        <td><%= Html.TextArea("TaskNotes", Model.TaskSchedule.Notes, new { @class = "smallTextarea" })%></td>
                    </tr>
                </table>
            <div id="task-audit-container">
                <label id="audit-label">Created: <%=Model.TaskSchedule.CreatedCompoundDisplay %> - Last Modified: <%=Model.TaskSchedule.LastModifiedCompoundDisplay %></label>
            </div>
            <% } %>
        </div>
    </div>
    <script type="text/javascript">
        <% if (ProjectTypeHelper.GetIsRevitServerProject(Model.CurrentProject.RevitServerVersion)) { %>
            var projectType = 'Revit';
        <% } else {  %>
            var projectType = '<%= Model.CurrentProject.RevitServerVersion %>';
        <% } %>

        function getProjectType()
        {
            return projectType;
        } 
        
        <% if ((Model.TaskSchedule.TaskInputParameters != null) && (Model.TaskSchedule.TaskInputParameters.Count > 0)) { %>
            <% string currentParent = null; %>
        <% foreach (TaskScheduleInputParameter taskInputParameter in Model.TaskSchedule.TaskInputParameters.OrderBy(tp => tp.Parent))
            { %>


                <% if (!String.IsNullOrEmpty(taskInputParameter.Parent)) {  %>
                    <% TaskScheduleInputParameter parentParameter = Model.TaskSchedule.TaskInputParameters.SingleOrDefault(tip => tip.Name == taskInputParameter.Parent); %>

                    <% if (currentParent != taskInputParameter.Parent) { %>
                        <% if (currentParent != null) { %> });<% } %>
                        <% if ((parentParameter != null) && (String.IsNullOrEmpty(parentParameter.Autocomplete))) { %>
                            $("#<%= parentParameter.CleanedName %>").change(function(e) {
                        <% } else { %>
                            $("#<%= parentParameter.CleanedName %>_value").change(function(e) {
                        <% } %>
                        <% currentParent = parentParameter.Name; %>
                    <% } %>

                    <%= taskInputParameter.GenerateParentJavascriptIfCondition(parentParameter) %>
                <% } %>
            <% } %>
            <% if (currentParent != null) { %> });<% } %>
            <% foreach (TaskScheduleInputParameter taskInputParameter in Model.TaskSchedule.TaskInputParameters.OrderBy(tp => tp.Parent))
            { %>
                <% TaskScheduleInputParameter parentParameter = Model.TaskSchedule.TaskInputParameters.SingleOrDefault(tip => tip.Name == taskInputParameter.Parent); %>

                <% if (!String.IsNullOrEmpty(taskInputParameter.Parent)) {  %>
                    <%= taskInputParameter.GenerateParentJavascriptIfCondition(parentParameter) %>
                <% } %>

                <%= taskInputParameter.GenerateVisibilityIfCondition(ProjectTypeHelper.GetAllProjectTypeValues(), Model.CurrentProject.RevitServerVersion) %>
                <% if (!String.IsNullOrEmpty(taskInputParameter.Scope)) {  %>
                    $("#Scope").change();
                <% } %>
            <% } %>
        <% } %>

    </script>
</asp:Content>
