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

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/d3.min.js" type="text/javascript"></script>
    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery-ui-1.14.0.min.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/rickshaw/rickshaw.min.css" />

    <style>
        #chart-container {
            position: relative;
        }
        #chart {
            margin-left: 40px;
        }
        #y_axis {
            position: absolute;
            top: 0;
            bottom: 0;
            width: 40px;
        }
        #chart-slider {
            margin-left: 40px;
        }
    </style>

    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/rickshaw/rickshaw.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        function viewMetric() {
            window.location.href = "<%= Url.Action("Graphs/" + Model.CurrentProject.ExternalId, "ModelMetrics") %>?model=" + encodeURIComponent($("#ServerModel").val()) + "&metric=" + encodeURIComponent($("#Metric").val());
        }

        function loadStoredMetrics() {
            $("#pinned-model-container").hide();
            $("#loading-container").show();

            $.ajax({
                url: '<%= Url.Action("LoadProjectMetrics", "ModelMetrics")%>',
                cache : false,
                data: {
                    projectId: '<%= Model.CurrentProject.ExternalId %>',
                    range: $("#metric-range-select").val()
                },
                type: "GET",
                success: function (response) {
                    $("#pinned-model-container").empty();
                    $("#pinned-model-container").html(response);
                    
                    $("#loading-container").hide();
                    $("#pinned-model-container").show();
                }
            });
        }

        function removeStoredMetrics() {
            $(".stored-metric-container").each(function() {
                var model = $(this).attr("model");
                var metric = $(this).attr("metric");
                
                $(".graph-action[model='" + model + "'][metric='" + metric + "']").hide();
            });
        }

        function storeMetricSortOrder() {
            var order = [];

            $("#pinned-model-container").children().each(function() {
                order.push($(this).attr("stored-metric-id"));
            });

            $.ajax({
                url: '<%= Url.Action("UpdateProjectMetricOrder", "ModelMetrics")%>',
                cache : false,
                data: {
                    projectId: '<%= Model.CurrentProject.ExternalId %>',
                    order: order.join(",")
                },
                type: "POST"
            });
        }

        function storeMetric(model, metric) {
            $.ajax({
                dataType: "html",
                url: '<%= Url.Action("InsertProjectMetric", "ModelMetrics")%>',
                cache : false,
                data: {
                    projectId: '<%= Model.CurrentProject.ExternalId %>',
                    model: model,
                    metric: metric,
                    range: $("#metric-range-select").val()
                },
                type: "POST",
                success: function (response) {
                    if (response.length > 0) {
                        $("#pinned-model-container").append(response);
                        $("#stored-metrics").show();
                    }

                    removeStoredMetrics();
                }
            });
        }

        function removeMetric(storedMetricId) {
            $("#pinned-error-container").empty();

            $.ajax({
                url: '<%= Url.Action("DeleteProjectMetric", "ModelMetrics")%>',
                cache : false,
                data: {
                    projectId: '<%= Model.CurrentProject.ExternalId %>',
                    storedMetricId: storedMetricId
                },
                type: "POST",
                success: function (response) {
                    if (response.length == 0) {
                        $("#stored-metric_" + storedMetricId).remove();

                        if ($(".stored-metric-container").length === 0) $("#stored-metrics").hide();
                    }
                    else $("#pinned-error-container").html(response);
                    
                    storeMetricSortOrder();

                    $(".graph-action").show();
                    removeStoredMetrics();
                }
            });
        }

        function generateExternalLink() {
            $.ajax({
                type: 'GET',
                url: '<%= Url.Action("GetExternalMetricsGraphLink", "ModelMetrics") %>',
                data: {
                    projectId: '<%= Model.CurrentProject.ExternalId %>',
                    model: '<%= HttpUtility.JavaScriptStringEncode(Model.SelectedServerModel) %>',
                    metric: '<%= HttpUtility.JavaScriptStringEncode(Model.SelectedMetricType) %>'
                },
                cache: false,
                success: function (response) {
                    $("#modal-overlay").html(response);
                },
                complete: function () {
                    showModelDialog();
                }
            });
        }
    </script>

    <div id="banner-space">
        <div id="banner-detail-container">
            <div class="left-floating-panel">
                <div id="project-title"><span><%= Model.CurrentProject.Name %></span><span id="project-number"><%= 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)); %>
            <div class="clear"></div>
        </div>
    </div>
    <div id="content-wrap">
        <% Html.RenderPartial("Navigation/_SideNavigation", Model.MenuNavigationModel); %>
	    <div id="content">
	        <h1>Model Metrics</h1>
            <div id="tab-container">
                <ul class="tabs">
			        <li><a href="<%= Url.Action("Index/" + Model.CurrentProject.ExternalId, "ModelMetrics") %>">Summary</a></li>
                    <li><a href="<%= Url.Action("Graphs/" + Model.CurrentProject.ExternalId, "ModelMetrics") %>" class="active">Graphs</a></li>
                </ul>
            </div>
            <br />
            <div id="stored-metrics"<% if (Model.StoredMetrics.Count == 0) { %> style="display:none"<% } %>>
                <div class="right-floating-panel">
                    <select id="metric-range-select" onchange="loadStoredMetrics()">
                        <option value="previous" selected="selected">Previous</option>
                        <option value="7days">7 Days</option>
                        <option value="30days">30 Days</option>
                    </select>
                </div>
                <div class="clear"></div>
                <div id="pinned-error-container" class="validation-summary-error"></div>
                <br />
                <div>
                    <div id="pinned-model-container" class="inner"><%= Html.Partial("Partials/StoredProjectMetrics", Model.StoredMetrics) %></div>
                    <div id="loading-container" class="loading-container" style="display:none"><img src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/loading.gif" title="Loading"/></div>
                </div>
                <hr />
            </div>
            <% if (Model.ServerModels.Count > 0)
               { %>
                <table class="center-floating-panel">
                    <tr>
                        <td>Model:</td>
                        <td>
                            <select id="ServerModel" name="ServerModel">
                                <% foreach (string serverModel in Model.ServerModels)
                                    { %>
                                    <option value="<%= serverModel %>" <% if (serverModel == Model.SelectedServerModel) { %> selected="selected"<% } %>><%= serverModel %></option>
                                <% } %>
                            </select>
                        </td>
                        <td style="padding-right:5px;">
                            <select id="Metric" name="Metric">
                                <% foreach (string operation in Model.MetricTypes)
                                    { %>
                                    <option value="<%= operation %>"<% if (operation == Model.SelectedMetricType) { %> selected="selected"<% } %>><%= operation %></option>
                                <% } %>
                            </select>
                        </td>
                        <td><input type="button" value="View" class="button" onclick="viewMetric()" /></td>
                    </tr>
                </table>
                <br />
                <% if (Model.ModelMetrics.Count > 0) { %>
                    <script type="text/javascript">
                        var modelSizeGraph = null,
                            metricGraph = null;
                    </script>
                    <%= Html.Partial("Partials/MetricGraph", Model.GetMetricGraphViewModel()) %><% if (ProjectTypeHelper.GetIsRevitServerProject(Model.CurrentProject.RevitServerVersion)) { %><br /><% } %><div class="graph-container">
                        <div id="graph-container_modelSize" class="graph-inner-container">
                            <div class="graph-header">Model Size (MB)</div>
                            <% if (Model.ModelMetrics.Count > 0)
                               { %>
                                <div id="chart-container_modelSize>">
                                    <div id="y_axis_modelSize"></div>
	                                <div id="chart_modelSize"></div>
                                </div>
                                <div id="chart_modelSize_modelEvents" class="chart_modelEvents"></div>
	                            <div id="chart-slider_modelSize"></div>
                                <script type="text/javascript">
                                    var palette = new Rickshaw.Color.Palette();

                                    var modelSizeGraph = new Rickshaw.Graph({
                                        element: document.getElementById("chart_modelSize"),
                                        renderer: 'multi',
                                        width: $("#graph-container_modelSize").width(),
                                        stack: false,
                                        dotSize: 6,
                                        series: [{
                                            name: 'Model Size (MB)',
                                            data: [
                                                <% foreach (RevitPerformance performanceMetric in Model.GetSizeModelMetrics())
                                                    { %>
                                                    <% if (performanceMetric != Model.GetSizeModelMetrics().First()) { %>,<% } %>{ x: <%= Model.ConvertToUnixTimestamp(performanceMetric.Created) %>, y: <%= Model.ConvertModelSizeToMB(performanceMetric.ModelSize) %> }
                                                <% } %>
                                            ],
                                            color: "steelblue",
                                            renderer: 'stack'
                                        }
                                        <% if(Model.ModelEvents.Count > 0) { %>
                                            , {
                                                renderer: 'stack',
                                                data: [
                                                    { x: <%= Model.ConvertToUnixTimestamp(Model.ModelEvents.FirstOrDefault().Created) %> - 100000, y: null },
                                                    { x: <%= Model.ConvertToUnixTimestamp(Model.ModelEvents.LastOrDefault().Created) %>, y: null },
                                                ]
                                            }
                                        <%}%>
                                        ]
                                    });

                                        new Rickshaw.Graph.RangeSlider.Preview({
                                        graph: modelSizeGraph,
                                        element: document.querySelector('#chart-slider_modelSize')
                                    });

                                        new Rickshaw.Graph.Axis.Time( {
                                        graph: modelSizeGraph,
                                        ticksTreatment: "graph-date"
                                    } );

                                        new Rickshaw.Graph.Axis.Y( {
                                        graph: modelSizeGraph
                                    } );

                                        new Rickshaw.Graph.HoverDetail( {
                                        graph: modelSizeGraph
                                    });

                                        var annotator = new Rickshaw.Graph.Annotate({
                                        graph: modelSizeGraph,
                                        element: document.getElementById('chart_modelSize_modelEvents')
                                    });


                                        <% foreach (ModelEvent modelEvent in Model.ModelEvents)
                                    { %>
                                    annotator.add('<%=Model.ConvertToUnixTimestamp( modelEvent.Created.ToLocalTime() )%>', '<%=modelEvent.EventType%> - <%=modelEvent.Detail%> on <%= DateTimeHelper.ToString(modelEvent.Created.ToLocalTime())%>')
                                        <% } %>

                                    annotator.update();

                                    modelSizeGraph.render();
                                </script>
                            <% } else { %>
                                <div><i>No performance metrics available</i></div>
                            <% } %>
                        </div>
                    </div><% if (ProjectTypeHelper.GetIsRevitServerProject(Model.CurrentProject.RevitServerVersion)) { %><div class="graph-container">
                            <div id="graph-container_supportSize" class="graph-inner-container">
                                <div class="graph-header">Support File Size (MB)</div>
                                <% if (Model.FileVersions.Count > 0)
                                   { %>
                                    <div id="chart-container_supportSize"">
                                        <div id="y_axis_supportSize""></div>
	                                    <div id="chart_supportSize"></div>
                                    </div>
	                                <div id="chart-slider_supportSize"></div>
                                    <script type="text/javascript">
                                        var palette = new Rickshaw.Color.Palette();

                                        var supportGraph = new Rickshaw.Graph({
                                            element: document.getElementById("chart_supportSize"),
                                            renderer: 'multi',
                                            width: $("#graph-container_supportSize").width(),
                                            stack: false,
                                            dotSize: 6,
                                            series: [{
                                                name: 'Support Size (MB)',
                                                data: [
                                                    <% foreach (RevitFileVersion revitFileVersion in Model.FileVersions)
                                                        { %>
                                                        <% if (revitFileVersion != Model.FileVersions.First())
                                                            { %>,<% } %>{ x: <%= Model.ConvertToUnixTimestamp(revitFileVersion.DateCreated) %>, y: <%= Model.ConvertModelSizeToMB(revitFileVersion.SupportFiles) %> }
                                                    <% } %>
                                                ],
                                                color: "steelblue",
                                                renderer: 'stack'
                                            }]
                                        });

                                        new Rickshaw.Graph.RangeSlider.Preview({
                                            graph: supportGraph,
                                            element: document.querySelector("#chart-slider_supportSize")
                                        });
            
                                        new Rickshaw.Graph.Axis.Time( {
                                            graph: supportGraph,
                                            ticksTreatment: "graph-date"
                                        } );
                        
                                        new Rickshaw.Graph.Axis.Y( {
                                            graph: supportGraph
                                        } );

                                        new Rickshaw.Graph.HoverDetail( {
                                            graph: supportGraph
                                        });

                                        supportGraph.render();
                                    </script>
                                <% }
                                   else
                                   { %>
                                    <div><i>No performance metrics available</i></div>
                                <% } %>
                            </div>
                        </div>
                    <% } %>
                    <div class="clear"></div>
                <% }
                   else
                   { %>
                    <div><%= TextHelper.GetText("This project has no performance metric data stored") %></div>
                <% } %>
            <% }
               else
               { %>
                <div><%= TextHelper.GetText("This project has no performance metric data stored") %></div>
            <% } %>
        </div>
    </div>
    <script type="text/javascript">
        removeStoredMetrics();

        $("#pinned-model-container").sortable({
            stop: function(event, ui) {
                storeMetricSortOrder();
            }
        });

        $(window).resize(function () {
            if (modelSizeGraph) {
                modelSizeGraph.configure({ width: $("#graph-container_modelSize").width() });
                modelSizeGraph.render();
            }

            if (metricGraph) {
                metricGraph.configure({ width: $("#graph-container").width() });
                metricGraph.render();
            }
        });
    </script>
</asp:Content>
