'use strict';
define(function() {
  var dynamicstylewidget = function(
    gcPropertiesLayers,
    gclayers,
    ngDialog,
    ogcFactory,
    $http,
    extendedNgDialog,
    FeatureTypeFactory,
    StyleFactory,
    gcWFS,
    ConfigFactory,
    $filter
  ) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/dynamicstyle/views/dynamicstylewidget.html',

      restrict: 'A',

      link: function(scope, elt, attrs, ctrl) {
        var map = scope.map;
        scope.resetWidget = function() {
          scope.current = {};
          scope.current.fti = {};
          scope.current.iteration = 5;
          scope.current.wsURL =
            'http://192.168.132.14/PPWSA-GIS-SERVICE/Service1_DMA?USER=U&PASSWORD=81dc9bdb52d04dc20036dbd8313ed055';
          scope.current.describeData = 'RESULTS';
          scope.resultData = {};
          scope.iteration = 5;
          scope.layeropacity = { value: 0 };
        };
        scope.resetWidget();
        var wgs84Sphere = new ol.Sphere(6378137);

        scope.tabs = [
          { title: 'dynamicstyle.layer' },
          { title: 'dynamicstyle.config' },
        ];
        scope.tabs.activeTab = 0;
        // Data correspondant au path
        scope.config = [];
        var sample = {
          wsURL:
            'http://192.168.132.14/PPWSA-GIS-SERVICE/Service1_DMA?USER=U&PASSWORD=81dc9bdb52d04dc20036dbd8313ed055',
          describeData: 'RESULTS',
          name: 'sample',
          fti: FeatureTypeFactory.getFeatureByUid(
            '19eb9b01-60c3-4f9b-96be-4539b9bcb720'
          ),
          type: 'number',
        };
        scope.config.push(sample);

        //scope.config.wsURL = 'http://192.168.132.14/PPWSA-GIS-SERVICE/Service1_DMA?USER=U&PASSWORD=81dc9bdb52d04dc20036dbd8313ed055';
        //scope.config.describeData = "RESULTS";
        scope.refreshData = function(wsUrl, describeData) {
          scope.getData(wsUrl, describeData);
        };
        /**
         * [refreshData description]
         * @param  {[type]} wsUrl        [description]
         * @param  {[type]} describeData [description]
         * @return {[type]}              [description]
         */
        scope.remove = function(key) {
          delete scope.theConfig[key];
          ConfigFactory.add(scope.theConfig, 'WSStyle', scope.ConfigName).then(
            function(res) {
              require('toastr').success(res);
            }
          );
          // console.log(key);
        };
        scope.verifyTypeofData = function(resultAttr) {
          console.log(resultAttr);
          console.log(typeof scope.resultData[0][resultAttr]);
          scope.current.minValue = Number(scope.resultData[0][resultAttr]);
          scope.current.maxValue = Number(scope.resultData[0][resultAttr]);
          angular.forEach(scope.resultData, function(value) {
            if (scope.current.minValue > Number(value[resultAttr])) {
              scope.current.minValue = Number(value[resultAttr]);
            }

            if (scope.current.maxValue < Number(value[resultAttr])) {
              scope.current.maxValue = Number(value[resultAttr]);
            }
          });
        };
        var hexToRgb = function(hex) {
          var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
          return result
            ? {
                r: parseInt(result[1], 16),
                g: parseInt(result[2], 16),
                b: parseInt(result[3], 16),
                a: 0.8,
              }
            : null;
        };

        scope.values = [];

        /**
         * Evenement d'ecoute de la variable scope.layeropacity
         * @param  {[type]} opacity){                                       ;                                                                    } [description]
         * @param  {[type]} 1          [description]
         * @return {[type]}            [description]
         */
        scope.$watch(
          'layeropacity',
          function(opacity) {
            if (scope.olLayer) {
              console.log(scope.layeropacity.value);

              scope.olLayer.setOpacity(1 - scope.layeropacity.value / 100);
            }
            //scope.canvasLayer.getSource().changed();
            //$rootScope.$broadcast('gcOperationalLayerChange',scope.currlayer,"opacity");
          },
          1
        );
        /**
         * [calculate description]
         * @param  {[type]} iteration [description]
         * @return {[type]}           [description]
         */
        scope.calculate = function(iteration) {
          console.log('calculate');
          var amplitude = Math.abs(
            scope.current.maxValue - scope.current.minValue
          );
          console.log(amplitude);
          var variant = amplitude / scope.current.iteration;
          console.log(variant);
          var current_value = angular.copy(scope.current.minValue);
          console.log(current_value);
          scope.current.interv = [];
          scope.current.interv.push(current_value);
          // scope.itera
          scope.currentPalette.data.nb = iteration;
          scope.current.gpalette = StyleFactory.paletteGenerator(
            scope.currentPalette.data
          );
          var i = 0;
          while (current_value < scope.current.maxValue) {
            var maxv = current_value + variant;
            scope.current.interv.push({
              hexa: '#' + scope.current.gpalette[i],
              color: hexToRgb(scope.current.gpalette[i]),
              max: Math.round(maxv * 100) / 100,
              min: Math.round(current_value * 100) / 100,
              name: '[' + current_value + ',' + maxv + ']',
            });
            current_value = current_value + variant;
            console.log(current_value);
            i++;
          }
        };

        /**
         * Open Palette Library
         */
        scope.currentPalette = {
          data: {
            id: 'tol-dv',
            nb: scope.iteration,
          },
          symbolType: 'POLYGON',
        };
        /**
         * [openPalettesLibrary description]
         * @return {[type]} [description]
         */
        scope.openPalettesLibrary = function() {
          ngDialog.open({
            template:
              'js/XG/widgets/mapapp/style/views/modals/modal.palettelibrary.html',
            className: 'ngdialog-theme-plain miniclose width600 nopadding',
            closeByDocument: false,
            scope: scope,
          });
        };

        /**
         * [getData description]
         * @param  {[type]} catchments_url [description]
         * @param  {[type]} describeData   [description]
         * @return {[type]}                [description]
         */
        scope.getData = function(catchments_url, describeData) {
          var promise = $http.get('/services/ogc/proxy?url=' + catchments_url);
          promise.then(function(res) {
            // ici a ameliorer
            scope.resultData = res.data[describeData];
          });
        };
        /**
         * [styleFunction description]
         * @param  {[type]} feature    [description]
         * @param  {[type]} resolution [description]
         * @return {[type]}            [description]
         */
        var styleFunction = function(feature, resolution) {
          var lnk = feature.get(scope.current.attrLink);

          for (var i = 0; i < scope.resultData.length; i++) {
            //console.log(scope.attrLink);
            //console.log(scope.resultData[i][scope.attrLink]);
            if (lnk == scope.resultData[i][scope.current.attrLinkWS]) {
              var value = Number(scope.resultData[i][scope.current.resultAttr]);
              for (var j = 0; j < scope.current.interv.length; j++) {
                if (
                  value <= scope.current.interv[j].max &&
                  value > scope.current.interv[j].min
                ) {
                  return [
                    new ol.style.Style({
                      fill: new ol.style.Fill({
                        color: scope.current.interv[j].hexa, //'rgba('+scope.interv[i].r+','+scope.interv[i].g+','+scope.interv[i].b+','+scope.interv[i].a+')'
                      }),
                    }),
                  ];
                }
              }
            }
          }

          return [
            new ol.style.Style({
              fill: new ol.style.Fill({
                color: 'rgba(255,255,255,0.4)',
              }),
            }),
          ];
        };

        scope.sresultAttr = function(resultAttr) {
          scope.current.resultAttr = resultAttr;
          console.log(scope.current.resultAttr);
        };
        scope.sattrLinkWS = function(attrLinkWS) {
          scope.current.attrLinkWS = attrLinkWS;
          console.log(scope.current.attrLinkWS);
        };
        scope.sattrLink = function(attrLink) {
          scope.current.attrLink = attrLink;
          console.log(scope.current.attrLink);
        };
        scope.olLayer;
        scope.applytoMap = function() {
          if (scope.olLayer) {
            map.removeLayer(scope.olLayer);
          }

          scope.olLayer = gcWFS.getOlLayerFromFeaturetypeInfo(
            scope.current.fti
          );
          scope.olLayer.setStyle(styleFunction);

          map.addLayer(scope.olLayer);
          /*olLayer.setStyle(
                               new ol.style.Style({
                                 fill: new ol.style.Fill({
                                   color:  'rgba(255,255,255,0.4)'
                                 })
                               })
                               );*/
          /*
var lst = olLayer.getSource().getFeatures();
                   console.log(lst);
angular.forEach(lst, function(feature) {
              var lnk =  feature.get(scope.attrLink)
              console.log(lnk);
                for (var i = 0; i < scope.resultData.length; i++) {
                  //console.log(scope.attrLink);
                  //console.log(scope.resultData[i][scope.attrLink]);
                  if (lnk == scope.resultData[i][scope.attrLinkWS] )
                  {
                      var value = Number(scope.resultData[i][scope.resultAttr] );
                      for (var i = 0; i < scope.interv.length; i++) {
                        if ( value < scope.interv[i].max && value < scope.interv[i].min)
                        {
                          feature.setStyle([
                               new ol.style.Style({
                                 fill: new ol.style.Fill({
                                   color: scope.interv[i].hexa//'rgba('+scope.interv[i].color.r+','+scope.interv[i].color.g+','+scope.interv[i].color.b+','+scope.interv[i].color.a+')'
                                 })
                               })]
                               );
                        }
                      };

                  }
                };

                   feature.setStyle(
               new ol.style.Style({
                 fill: new ol.style.Fill({
                   color:  'rgba(255,255,255,0.4)'
                 })
               })
             );

});*/

          var lst = scope.olLayer.getSource().getFeatures();
          console.log(lst);
        };
        /*
                if(angular.isDefined(scope.geojson))
                {


                    var geojsonObject = scope.geojson;
                    console.log(scope.data);
                     var vectorSource = new ol.source.Vector({
                    features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
                  });
                    var vectorLayer = new ol.layer.Vector({
                    source: vectorSource,
                    style: styleFunction
                  });

                   map.addLayer(vectorLayer);

          scope
*/
        scope.theConfig = {};
        ConfigFactory.get('WSStyle', scope.ConfigName).then(function(res) {
          if (!res.data == '') {
            scope.theConfig = res.data;
          }
        });
        scope.currentmap;

        /**
         * [getCheckedTrue description]
         * @param  {[type]} name [description]
         * @return {[type]}      [description]
         */
        scope.getCheckedTrue = function(name) {
          console.log(name);
          if (!angular.isUndefined(scope.currentmap)) {
            if (scope.currentmap != name) {
              scope.theConfig[scope.currentmap].check = false;
              scope.map.removeLayer(scope.olLayer);
            }
          }

          if (scope.currentmap != name) {
            scope.currentmap = name;

            scope.current = angular.copy(scope.theConfig[name]);
            scope.theConfig[name].check = true;

            var promise = $http.get(
              '/services/ogc/proxy?url=' + scope.current.wsURL
            );
            promise.then(function(res) {
              // ici a ameliorer
              scope.resultData = res.data[scope.current.describeData];
              console.log(scope.resultData);
              scope.applytoMap();
            });
          } else {
            if (scope.theConfig[scope.currentmap].check == false) {
              scope.currentmap = name;

              scope.theConfig[scope.currentmap].check = true;

              scope.current = scope.theConfig[name];
              scope.theConfig[name].check = true;

              var promise = $http.get(
                '/services/ogc/proxy?url=' + scope.current.wsURL
              );
              promise.then(function(res) {
                // ici a ameliorer
                scope.resultData = res.data[scope.current.describeData];
                console.log(scope.resultData);
                scope.applytoMap();
              });
            } else {
              scope.theConfig[scope.currentmap].check = false;
              scope.map.removeLayer(scope.olLayer);
            }
          }

          return true;
        };
        //TDO le remove
        scope.Remove = function(name) {
          console.log(name);
          // scope.theConfig[name]=scope.current;
          ConfigFactory.add(scope.theConfig, 'WSStyle', scope.ConfigName).then(
            function(res) {
              require('toastr').success(res);
            }
          );
        };
        scope.Save = function(name) {
          console.log(name);
          //scope.current.check=false;
          scope.theConfig[name] = scope.current;
          ConfigFactory.add(scope.theConfig, 'WSStyle', scope.ConfigName).then(
            function(res) {
              require('toastr').success(res);
            }
          );
        };
        scope.open = function(name) {
          scope.currentFti = scope.config[0].fti;
          extendedNgDialog.open({
            template:
              'js/XG/widgets/mapapp/dynamicstyle/views/modals.dynamic.html',
            className:
              'ngdialog-theme-plain overflowY width400 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
            title: $filter('translate')('dynamicStyle'),
            draggable: true,
          });
        };
      },
    };
  };
  dynamicstylewidget.$inject = [
    'gcPropertiesLayers',
    'gclayers',
    'ngDialog',
    'ogcFactory',
    '$http',
    'extendedNgDialog',
    'FeatureTypeFactory',
    'StyleFactory',
    'gcWFS',
    'ConfigFactory',
    '$filter',
  ];
  return dynamicstylewidget;
});
