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

<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 } ); %>
    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery-ui-1.14.0.min.js" type="text/javascript"></script>
    <script src="https://code.jquery.com/jquery-migrate-3.0.0.min.js"></script>
    <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>
    <link href='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Content/Bootstrap/bootstrap.min.css?_v=<%=DateTime.UtcNow.Ticks %>' rel="stylesheet" type="text/css" />
    <% 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.CurrentTaskSchedule.TaskType.ToLower() %>';
            if (taskType && taskType === 'tasksequence') {

                $("#Scope").change(function () {
                    loadTaskSequence($("#Scope option:selected").text());
                });

                $("#ProjectId").change(function () {
                    loadTaskSequence($("#Scope option:selected").text());
                });

                $('#btn-update-and-run').prop('disabled', true);
                $('#btn-update').prop('disabled', true);
                const scope = '<%= Model.CurrentTaskSchedule.Scope %>';
                await loadTaskSequence(scope)
                $('#btn-update-and-run').prop('disabled', false);
                $('#btn-update').prop('disabled', false);
            }
        }

        async function loadTaskSequence(scope) {
            const taskScheduleId = '<%= Model.CurrentTaskSchedule.Id %>';
            const externalId = $("#ProjectId").val();
            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", "Task") %>";
        }

        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.CurrentTaskSchedule.Validation)) { %>
                try {
                    var validate = <%= Model.CurrentTaskSchedule.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.CurrentTaskSchedule.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.CurrentTaskSchedule.Id, "Task") %>");
                
            if (!taskSubmitted) {
                taskSubmitted = true;
            
                $("#CurrentTaskSchedule").submit();
            }
        }
    </script>
    <div id="content-wrap">
        <% Html.RenderPartial("Navigation/_SideNavigation", Model.MenuNavigationModel); %>
        <div id="content">
            <% using (Html.BeginForm("UpdateTaskSchedule/" + Model.CurrentTaskSchedule.Id, "Task", new { returnTo = Model.ReturnTo }, FormMethod.Post, new { @id = "CurrentTaskSchedule" }))
                { %> 
	            <div class="left-floating-panel"><h1>Setup Tasks</h1></div>
                <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>
                <div class="clear"></div>
                <% if (Model.TaskTemplate != null) { %>
                    <div class="left-floating-panel">
                        <div>
                            <div class="table-row">
                                <div class="table-cell"><h2 class="right-margin"><%= Html.Encode(Model.CurrentTaskSchedule.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.CurrentTaskSchedule.TaskTypeName)%></h2></div>
                <% } %>
                <div class="right-floating-panel"><a href="<%= WebHelpHelper.GetWebHelpURL(((LicenseType)ViewData["LicenseType"])) %>index.htm#t=Admin_%26_Coordinators_Guide%2FProject_Setup%2FTasks%2FAdding_Tasks.htm" target="_blank">Task Help</a></div>
                <div class="clear"></div>
                <% Html.RenderPartial("Task/EditTaskDetail", new EditTaskDetailViewModel(Model.CurrentTaskSchedule, Model.Projects, Model.TaskScopes, Model.TaskScheduleHours, Model.TaskScheduleMinutes, Model.PostActions, Model.DisabledPostTaskActions, Model.DefaultOnlyOnChange, Model.CurrentTaskSchedulePostTaskActionParameters, maxDaysForWeeklyScheduledTasks: Model.MaxDaysForWeeklyScheduledTasks)); %>
                <% if (Model.CurrentTaskSchedule.TaskType.ToLower() != "tasksequence")
                    { %>
                    <% if ((!String.IsNullOrEmpty(Model.CurrentTaskSchedule.HelpURL)) || (!String.IsNullOrEmpty(Model.CurrentTaskSchedule.ConfigHeader)))
                        { %>
                        <hr />
                    <% } %>
                    <div id="validation-error" class="validation-summary-error left-floating-panel" style="margin-bottom:15px;display:none;"></div>
                    <% if (!String.IsNullOrEmpty(Model.CurrentTaskSchedule.HelpURL))
                        { %>
                        <div class="right-floating-panel"><a href="<%= TaskHelper.GenerateTaskPluginHelpURL(((LicenseType)ViewData["LicenseType"]), Model.CurrentTaskSchedule.HelpURL) %>" target="_blank"><%= Html.Encode(Model.CurrentTaskSchedule.TaskTypeName)%> Help</a></div>
                    <% } %>
                    <div class="clear"></div>
                    <% if (!String.IsNullOrEmpty(Model.CurrentTaskSchedule.ConfigHeader))
                        { %>
                        <p><%= Html.Raw(Model.CurrentTaskSchedule.ConfigHeader) %></p>
                    <% } %>
                     <% if (AdministratorConsole.CustomTaskViewFactory.HasCustomView(Model.CurrentTaskSchedule.TaskType)  && Model.CurrentTaskSchedule.TaskInputParameters.Count > 0) { %>
                        <% Html.RenderPartial(AdministratorConsole.CustomTaskViewFactory.GetCustomView(Model.CurrentTaskSchedule.TaskType), AdministratorConsole.CustomTaskViewFactory.GetCustomViewModel(Model.CurrentTaskSchedule)); %>
                    <%} else if ((Model.CurrentTaskSchedule.TaskInputParameters != null) && (Model.CurrentTaskSchedule.TaskInputParameters.Count > 0))
                        { %>
                        <% for (int i = 0; i < Model.CurrentTaskSchedule.TaskInputParameters.Count; i++) { %>
                            <% 
                                string parameterValue = Model.CurrentTaskSchedule.TaskInputParameters[i].ParameterDefault;
                                if (Model.CurrentTaskSchedule.GetTaskParameter(Model.CurrentTaskSchedule.TaskInputParameters[i].Name).Trim().Length > 0) parameterValue = Model.CurrentTaskSchedule.GetTaskParameter(Model.CurrentTaskSchedule.TaskInputParameters[i].Name);
                            %>
                            <% Html.RenderPartial("Task/TaskScheduleInputParameter", new AdministratorConsole.Models.Shared.TaskController.TaskScheduleInputParameterViewModel() {
                                    TaskScheduleInputParameter = Model.CurrentTaskSchedule.TaskInputParameters[i],
                                    TaskScheduleParameters = Model.CurrentTaskSchedule.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.CurrentTaskSchedule.Notes)%></td>
                    </tr>
                </table>
            <div id="task-audit-container">
                <label id="audit-label">Created: <%=Model.CurrentTaskSchedule.CreatedByDisplay %> - Last Modified: <%=Model.CurrentTaskSchedule.LastModifiedDisplay %></label>
            </div>
            <% } %>
        </div>
    </div>
    <script type="text/javascript">
        var allProjectTypes = {};
        <% foreach (Project project in Model.Projects) { %>
            <% if (ProjectTypeHelper.GetIsRevitServerProject(project.RevitServerVersion)) { %>
                allProjectTypes['<%= project.ExternalId %>'] = 'Revit';
            <% } else { %>
                allProjectTypes['<%= project.ExternalId %>'] = '<%= project.RevitServerVersion %>';
            <% } %>
        <% } %>

        function getProjectType()
        {
            if (allProjectTypes[$("#ProjectId").val()] != null) return allProjectTypes[$("#ProjectId").val()];
            else return "";
        } 
        
        <% if (Model.CurrentTaskSchedule.TaskInputParameters != null) { %>
            <% string currentParent = null; %>
        <% foreach (TaskScheduleInputParameter taskInputParameter in Model.CurrentTaskSchedule.TaskInputParameters.OrderBy(tp => tp.Parent))
                { %>

                <% if (!String.IsNullOrEmpty(taskInputParameter.Parent)) {  %>
                    <% TaskScheduleInputParameter parentParameter = Model.CurrentTaskSchedule.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.CurrentTaskSchedule.TaskInputParameters.OrderBy(tp => tp.Parent))
                { %>
                <% TaskScheduleInputParameter parentParameter = Model.CurrentTaskSchedule.TaskInputParameters.SingleOrDefault(tip => tip.Name == taskInputParameter.Parent); %>

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

                <% if (!String.IsNullOrEmpty(taskInputParameter.ProjectType)) { %>
                    $("#ProjectId").change();
                <% } %>

                <% if (!String.IsNullOrEmpty(taskInputParameter.Scope)) {  %>
                    $("#Scope").change();
                <% } %>
            <% } %>
        <% } %>

        
    </script>
</asp:Content>
