'use strict';

define(function() {
  /*
   * dashboardCtrl
   */
  var dashboardCtrl = function(
    $scope,
    AncAppSearchFactory,
    ElasticFactory,
    $http,
    chartFactory,
    $filter,
    gaJsUtils,
    $timeout
  ) {
    //$scope.dashboards = ["1"];

    function createDefaultChart() {
      $scope.dashboards = [];

      /* ------------------------------- */
      var times = function(n) {
        return Array.apply(null, new Array(n));
      };

      var data = times(52)
        .map(Math.random)
        .reduce(
          function(data, rnd, index) {
            data.labels.push(index + 1);
            data.series.forEach(function(series) {
              series.push(Math.random() * 100);
            });

            return data;
          },
          {
            labels: [],
            series: times(4).map(function() {
              return new Array();
            }),
          }
        );

      var options = {
        showLine: false,
        axisX: {
          labelInterpolationFnc: function(value, index) {
            return index % 13 === 0 ? 'W' + value : null;
          },
        },
      };

      var responsiveOptions = [
        [
          'screen and (min-width: 640px)',
          {
            axisX: {
              labelInterpolationFnc: function(value, index) {
                return index % 4 === 0 ? 'W' + value : null;
              },
            },
          },
        ],
      ];

      /* ------------------------------- */
      var data3 = {
        series: [5, 3, 4],
      };

      var sum = function(a, b) {
        return a + b;
      };

      var chart1 = new Chartist.Line(
        '.ct1',
        {
          labels: [1, 2, 3, 4, 5, 6, 7, 8],
          series: [[5, 9, 7, 8, 5, 3, 5, 4]],
        },
        {
          low: 0,
          showArea: true,
        }
      );

      new Chartist.Line('.ct2', data, options, responsiveOptions);

      new Chartist.Pie('.ct3', data3, {
        labelInterpolationFnc: function(value) {
          return Math.round((value / data.series.reduce(sum)) * 100) + '%';
        },
      });

      /* ------------------------ */
      var chart4 = new Chartist.Pie(
        '.ct4',
        {
          series: [10, 20, 50, 20, 5, 50, 15],
          labels: [1, 2, 3, 4, 5, 6, 7],
        },
        {
          donut: true,
          showLabel: false,
        }
      );

      chart4.on('draw', function(data) {
        if (data.type === 'slice') {
          // Get the total path length in order to use for dash array animation
          var pathLength = data.element._node.getTotalLength();

          // Set a dasharray that matches the path length as prerequisite to animate dashoffset
          data.element.attr({
            'stroke-dasharray': pathLength + 'px ' + pathLength + 'px',
          });

          // Create animation definition while also assigning an ID to the animation for later sync usage
          var animationDefinition = {
            'stroke-dashoffset': {
              id: 'anim' + data.index,
              dur: 1000,
              from: -pathLength + 'px',
              to: '0px',
              easing: Chartist.Svg.Easing.easeOutQuint,
              // We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
              fill: 'freeze',
            },
          };

          // If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
          if (data.index !== 0) {
            animationDefinition['stroke-dashoffset'].begin =
              'anim' + (data.index - 1) + '.end';
          }

          // We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
          data.element.attr({
            'stroke-dashoffset': -pathLength + 'px',
          });

          // We can't use guided mode as the animations need to rely on setting begin manually
          // See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
          data.element.animate(animationDefinition, false);
        }
      });

      // For the sake of the example we update the chart every time it's created with a delay of 8 seconds
      chart4.on('created', function() {
        if (window.__anim21278907124) {
          clearTimeout(window.__anim21278907124);
          window.__anim21278907124 = null;
        }
        window.__anim21278907124 = setTimeout(
          chart4.update.bind(chart4),
          10000
        );
      });
    }

    function correctProperties(attributes, features) {
      var attrArray = new Array();
      attributes.forEach(function(element) {
        if (attrArray.indexOf(element.name) === -1)
          attrArray.push(element.name);
      });
      features.forEach(function(feature) {
        var propKeys = Object.keys(feature.properties);
        if (propKeys.length != attrArray.length) {
          var diff = $.grep(attrArray, function(el) {
            return $.inArray(el, propKeys) == -1;
          });
          diff.forEach(function(el) {
            feature.properties[el] = null;
          });
        }
      });
    }

    $scope.dashBoardLoaded = {};
    function getQueryData(idx, dashboards, collection) {
      var x = dashboards[idx];
      console.log(x);

      var promise;
      if (x.searchquery && x.searchquery.opts)
        promise = ElasticFactory.searchInTypeAnc(
          x.fti.name,
          'geojson',
          x.searchquery
        );
      else
        promise = ElasticFactory.searchInType(
          x.fti.name,
          'geojson',
          x.searchquery
        );

      promise.then(
        function(res) {
          correctProperties(x.fti.attributes, res.data.features);
          x.resultsearch = res.data;
          x.result = x.resultsearch.features;

          if (x.chartoptions.chart.tooltip) {
            var configdefault = chartFactory.getOptionsByType(
              x.chartoptions.chart.type
            );
            x.chartoptions.chart.tooltip = configdefault.tooltip;
          }

          if (x.chartoptions.chart.type == 'discreteBarChart') {
            if (
              gaJsUtils.checkNestedProperty('chartoptions.chart.height', x) &&
              gaJsUtils.checkNestedProperty(
                'chartoptions.chart.margin.bottom',
                x
              )
            ) {
              x.chartoptions.chart.height += 200;
              x.chartoptions.chart.margin.bottom += 200;

              // si staggerLabels => true pas possible de rotate les xAxis
              x.chartoptions.chart.staggerLabels = false;
              // x.chartoptions.chart.margin.bottom = 170;
              x.chartoptions.chart.xAxis.showMaxMin = false;
              x.chartoptions.chart.xAxis.rotateLabels = 80;
            }
          }

          var chartConfig = {
            source: {
              fti: x.fti,
              featureCollection: x.resultsearch,
              selected: true,
            },
            cql_filter: {
              attribute: x.attrchoice.choice,
              where: '1=1',
              total: x.attrchoice.total,
            },
            options: x.chartoptions,
            data: [],
          };
          var url = '/services/{portalid}/stats/charts/getChartData';

          // console.log(chartConfig);

          $http
            .post(url, chartConfig, { timeout: 100000000000 })
            .then(function(response) {
              x.chartdata = response.data.data;
              collection.insertAt(x.position, x);
              console.log(collection.getLength(), dashboards.length);

              if (collection.getLength() === dashboards.length) {
                $scope.dashboards = collection.getArray();
              } else {
                $scope.dashboards = collection.getArray();
                //var Ω =Math.floor(Math.random() * 3000) + 1000;
                // console.log(Ω);

                //$timeout(function(){
                getQueryData(idx + 1, dashboards, collection);
                // }, Ω);
              }
            });
        },
        function(error) {
          //gaDomUtils.hideGlobalLoader();
          require('toastr').error(
            $filter('translate')('elastic.search.search_failed')
          );
        }
      );
    }

    AncAppSearchFactory.getConfig().then(
      function(res) {
        if (res.data.etat === 'fini') {
          var dashboards = JSON.parse(res.data.content);
          $scope.nbDashboards = new Array(dashboards.length);
          var collection = new ol.Collection();
          if (dashboards.length > 0) getQueryData(0, dashboards, collection);
          else createDefaultChart();
        } else {
          createDefaultChart();
        }
      },
      function() {
        console.info('aucune configuration du dashboard');
      }
    );
  };

  dashboardCtrl.$inject = [
    '$scope',
    'AncAppSearchFactory',
    'ElasticFactory',
    '$http',
    'chartFactory',
    '$filter',
    'gaJsUtils',
    '$timeout',
  ];
  return dashboardCtrl;
});
