define([
  'angular',
  'lodash',
],
function (angular, _) {
  'use strict';

  var module = angular.module('grafana.controllers');

  module.controller('KairosDBQueryCtrl', function($scope, $timeout) {

    $scope.init = function() {
      $scope.target.errors = validateTarget($scope.target);
      $scope.aggregators = [
        { id: 'avg', name: 'avg' },
        { id: 'dev', name: 'dev' },
        { id: 'div', name: 'div' },
        { id: 'min', name: 'min' },
        { id: 'max', name: 'max' },
        { id: 'rate', name: 'rate' },
        { id: 'sum', name: 'sum' },
        { id: 'scale', name: 'scale' },
        { id: 'count', name: 'count' },
        { id: 'least_square', name: 'least square' },
        { id: 'percentile', name: 'Ppercentile' }
      ];
      $scope.timeUnits = ['years', 'moths', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'miliseconds'];
      $scope.suggestedMetrics = [];

      if (!$scope.target.aggregator) {
        $scope.target.aggregator = 'sum';
      }

      $scope.getAvailableMetrics();

      $scope.$on('typeahead-updated', function() {
        $timeout($scope.targetBlur);
      });
    };

    $scope.targetBlur = function() {
      $scope.target.errors = validateTarget($scope.target);

      // this does not work so good
      if (!_.isEqual($scope.oldTarget, $scope.target) && _.isEmpty($scope.target.errors)) {
        $scope.oldTarget = angular.copy($scope.target);
        $scope.get_data();
      }
    };

    $scope.duplicate = function() {
      var clone = angular.copy($scope.target);
      $scope.panel.targets.push(clone);
    };

    $scope.getAvailableMetrics = function() {
      $scope.datasource
        .performSuggestMetrics()
        .then(function(result) {
          $scope.suggestedMetrics = result;
        });
    };

    $scope.suggestTagKeys = function(query, callback) {
      $scope.datasource
        .performSuggestTags($scope.target)
        .then(callback);
    };

    $scope.suggestTagValues = function(query, callback) {
      $scope.datasource
        .performSuggestTags($scope.target, $scope.target.currentTagKey)
        .then(callback);
    };

    $scope.addTag = function() {
      if (!$scope.addTagMode) {
        $scope.addTagMode = true;
        return;
      }

      if (!$scope.target.tags) {
        $scope.target.tags = [];
      }

      $scope.target.errors = validateTarget($scope.target);

      if (!$scope.target.errors.tags) {
        var tag = {
          key: $scope.target.currentTagKey,
          value:$scope.target.currentTagValue
        };
        $scope.target.tags.push(tag);
        $scope.target.currentTagKey = '';
        $scope.target.currentTagValue = '';
        $scope.targetBlur();
      }

      $scope.addTagMode = false;
    };

    $scope.removeTag = function(i) {
      $scope.target.tags.splice(i, 1);
      $scope.targetBlur();
    };

    $scope.addGroup = function() {
      if (!$scope.addGroupMode) {
        $scope.addGroupMode = true;
        return;
      }

      if (!$scope.target.groups) {
        $scope.target.groups = [];
      }

      $scope.target.errors = validateTarget($scope.target);

      if (!$scope.target.errors.groups) {
        $scope.target.groups.push($scope.target.currentGroup);
        $scope.target.currentGroup = '';
        $scope.targetBlur();
      }

      $scope.addGroupMode = false;
    };

    $scope.removeGroup = function(i) {
      $scope.target.groups.splice(i, 1);
      $scope.targetBlur();
    };

    function validateTarget(target) {
      var errs = {};

      if (!target.metric) {
        errs.metric = "You must supply a metric name.";
      }

      if (!target.sampling || !target.sampling.unit || !target.sampling.value) {
        errs.sampling = "You must supply a sampling unit and value."
      }

      return errs;
    }

  });

});
