/*
 * Copyright 2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global glowroot, angular, $ */

glowroot.controller('TransactionPercentilesCtrl', [
  '$scope',
  '$location',
  '$http',
  '$filter',
  '$timeout',
  'charts',
  'modals',
  function ($scope, $location, $http, $filter, $timeout, charts, modals) {

    $scope.$parent.activeTabItem = 'time';

    if ($scope.last) {
      // force the sidebar to update
      $scope.$parent.chartRefresh++;
    }

    var chartState = charts.createState();

    function refreshData() {
      charts.refreshData('backend/transaction/percentiles', chartState, $scope.$parent, addToQuery, onRefreshData);
    }

    $scope.$watchGroup(['chartFrom', 'chartTo', 'chartRefresh'], function () {
      refreshData();
    });

    $scope.clickTopRadioButton = function (item, event) {
      if (item === 'percentiles') {
        $scope.$parent.chartRefresh++;
      } else {
        $location.url('transaction/average' + $scope.tabQueryString());
      }
    };

    $scope.clickActiveTopLink = function (event) {
      if (!event.ctrlKey) {
        $scope.$parent.chartRefresh++;
        // suppress normal link
        event.preventDefault();
        return false;
      }
    };

    $scope.openCustomPercentilesModal = function () {
      $scope.customPercentiles = $scope.percentiles.join(', ');
      modals.display('#customPercentilesModal', true);
      $timeout(function () {
        $('#customPercentiles').focus();
      });
    };

    $scope.applyCustomPercentiles = function () {
      var percentiles = [];
      angular.forEach($scope.customPercentiles.split(','), function (percentile) {
        percentile = percentile.trim();
        if (percentile.length) {
          percentiles.push(Number(percentile));
        }
      });
      $scope.percentiles = sortNumbers(percentiles);
      if (angular.equals($scope.percentiles, $scope.layout.defaultPercentiles)) {
        $location.search('percentile', null);
      } else {
        $location.search('percentile', $scope.percentiles);
      }
      $('#customPercentilesModal').modal('hide');
      $scope.$parent.chartRefresh++;
    };

    function onLocationChangeSuccess() {
      if ($location.search().percentile) {
        var percentiles = [];
        angular.forEach($location.search().percentile, function (percentile) {
          percentiles.push(Number(percentile));
        });
        $scope.percentiles = sortNumbers(percentiles);
      } else {
        $scope.percentiles = $location.search().percentile || $scope.layout.defaultPercentiles;
      }
    }

    function sortNumbers(arr) {
      return arr.sort(function (a, b) {
        return a - b;
      });
    }

    $scope.$on('$locationChangeSuccess', onLocationChangeSuccess);
    onLocationChangeSuccess();

    function addToQuery(query) {
      query.percentile = $scope.percentiles;
    }

    function onRefreshData(data, query) {
      $scope.transactionCounts = data.transactionCounts;
      $scope.lastDurationMillis = query.to - query.from + 1000 * $scope.layout.fixedAggregateIntervalSeconds;
      $scope.mergedAggregate = data.mergedAggregate;
    }

    var chartOptions = {
      tooltip: true,
      series: {
        stack: false,
        lines: {
          fill: false
        }
      },
      tooltipOpts: {
        content: function (label, xval, yval, flotItem) {
          var from = xval - chartState.dataPointIntervalMillis;
          // this math is to deal with active aggregate
          from = Math.ceil(from / chartState.dataPointIntervalMillis) * chartState.dataPointIntervalMillis;
          var to = xval;
          return charts.renderTooltipHtml(from, to, $scope.transactionCounts[xval], flotItem.dataIndex,
              flotItem.seriesIndex, chartState.plot, function (value) {
                return $filter('gtMillis')(value) + ' milliseconds';
              });
        }
      }
    };

    charts.init(chartState, $('#chart'), $scope.$parent);
    charts.plot([[]], chartOptions, chartState, $('#chart'), $scope.$parent);
    charts.initResize(chartState.plot, $scope);
  }
]);

@@ -1045,24 +1045,53 @@
 teState();%0A%0A
+    var appliedPercentiles;%0A%0A
     function
@@ -1305,24 +1305,235 @@
 nction () %7B%0A
+      if (angular.equals(appliedPercentiles, $scope.layout.defaultPercentiles)) %7B%0A        $location.search('percentile', null);%0A      %7D else %7B%0A        $location.search('percentile', appliedPercentiles);%0A      %7D%0A
       refres
@@ -2093,24 +2093,24 @@
 tiles = 
-$scope.p
+appliedP
 ercentil
@@ -2319,29 +2319,32 @@
  () %7B%0A      
-var p
+appliedP
 ercentiles =
@@ -2506,33 +2506,40 @@
 th) %7B%0A          
-p
+appliedP
 ercentiles.push(
@@ -2589,265 +2589,40 @@
     
-$scope.percentiles = sortNumbers(percentiles);%0A      if (angular.equals($scope.percentiles, $scope.layout.defaultPercentiles)) %7B%0A        $location.search('percentile', null);%0A      %7D else %7B%0A        $location.search('percentile', $scope.percentiles);%0A      %7D
+sortNumbers(appliedPercentiles);
 %0A   
@@ -2750,24 +2750,80 @@
 Success() %7B%0A
+      var priorAppliedPercentiles = appliedPercentiles;%0A
       if ($l
@@ -2861,21 +2861,24 @@
         
-var p
+appliedP
 ercentil
@@ -2967,33 +2967,40 @@
 le) %7B%0A          
-p
+appliedP
 ercentiles.push(
@@ -3039,37 +3039,16 @@
 %0A       
- $scope.percentiles =
  sortNum
@@ -3052,17 +3052,24 @@
 Numbers(
-p
+appliedP
 ercentil
@@ -3100,83 +3100,268 @@
     
-$scope.percentiles = $location.search().percentile %7C%7C $scope.layout.default
+appliedPercentiles = $scope.layout.defaultPercentiles;%0A      %7D%0A%0A      if (priorAppliedPercentiles !== undefined && !angular.equals(appliedPercentiles, priorAppliedPercentiles)) %7B%0A        $scope.$parent.chartRefresh++;%0A      %7D%0A      $scope.percentiles = applied
 Perc
@@ -3369,24 +3369,16 @@
 ntiles;%0A
-      %7D%0A
     %7D%0A%0A 
@@ -3414,23 +3414,16 @@
 %7B%0A      
-return 
 arr.sort
@@ -3637,24 +3637,24 @@
 ntile = 
-$scope.p
+appliedP
 ercentil

Fix browser back/forward when changing percentiles