'use strict';
define(() => {
  var dashboardHpoEnrichment = (
    HpoCarteAppFactory,
    HpoDataVisServices,
    FeatureTypeFactory,
    HpoAppServices,
    gaDomUtils,
    $q,
    $rootScope,
    $filter,
    gcMapUtils
  ) => {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/home_admin_data/views/utilities/data/dashboard_hpo_enrichment.html',
      restrict: 'EA',
      link: (scope) => {
        scope.downloadEnrichment = () => {
          HpoAppServices.downloadEnrichment(scope.objStandardisation.properties.SELECTED_JEU);
        }
        var cfg = HpoCarteAppFactory.getInitProvider().getHpoConfig();
        scope.baseMap = cfg.baseMap?cfg.baseMap:'toner-lite';
        scope.portalid = $rootScope.xgos.portal.uid;
        const colors = ['#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a','#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
        '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb','#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8',
        '#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a','#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
        '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb','#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8',
        '#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a','#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
        '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb','#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8',
        '#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a','#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
        '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb','#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8',
        '#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a','#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
        '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb','#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8']
        let promises = [];
        gaDomUtils.showGlobalLoader();
          let promiseGetGeometryFromS3= HpoDataVisServices.getEnrichmentGeometry(scope.objStandardisation.properties.SELECTED_JEU).then((res)=>{
            let layers = [];
            let source;
            scope.layersDefiniton = [];
            if(!scope.baseMap || scope.baseMap === 'osm'){
              source = new ol.source.OSM();
            } else {
              source = new ol.source.XYZ({ 
                url:'http://{1-4}.basemaps.cartocdn.com/'+scope.baseMap+'/{z}/{x}/{y}.png',
              })
            }
            layers.push(new ol.layer.Tile({
              source: source,
            }));
            
            let count = 0;
            let geometriesAll= [];
            let visible = true;
            let srid;
            Object.keys(res.data).forEach(key => {
              srid = res.data[key].srid;
              let geometryTemp = generateGeometry(res.data, key, layers, count, scope.layersDefiniton, visible);
              geometriesAll = [...geometryTemp, ...geometriesAll];
              count++;
              visible = false;
            })
            let vectorAll = new ol.layer.Vector({
              source: new ol.source.Vector({
                  features: geometriesAll
              })
            });
            let extent = geometriesAll.length>0?vectorAll.getSource().getExtent():[0,0,0,0];
            var map = new ol.Map({
              layers: layers,
              interactions: ol.interaction.defaults({mouseWheelZoom: false}).extend([gcMapUtils.altZoomInteraction()]),
              target: 'enrichMap',
              view: new ol.View({
                projection: srid,
                center: ol.extent.getCenter(extent),
                zoom: 13,
              }),
              ol3Logo: false,
            });
            map.getView().fit(extent,map.getSize());
            scope.addRemoveLayer =  (layer) =>{
              if(layer.visible){
                map.addLayer(layer.vector);
              } else {
                map.removeLayer(layer.vector);
              }
            }
            scope.enrichMap = true;
          });
          promises.push(promiseGetGeometryFromS3);
          $q.all(promises).then(()=>{
            gaDomUtils.hideGlobalLoader();
          }, () =>{
            gaDomUtils.hideGlobalLoader();
          });
          scope.layerVisibility = (position) => {
            let layer = scope.layersDefiniton[position];
            layer.visible = !layer.visible;
            scope.addRemoveLayer(layer);
          }


          let generateGeometry = (features, name, layers, count, layersDefiniton, visible) => {
            let geometryTemp = [];
            let type = features[name].geometry[0].geometry.type;
            let style;
            let color = colors[count];
            style = generateStyle(type, style, color);
            features[name].geometry.forEach((g) => {
              let feature = gcMapUtils.toGeometry(g);
              if (feature)
                geometryTemp.push(feature);
              type = g.geometry.type;
              if(g.colour){
                style = generateStyle(type, style, g.colour);
                color = g.colour;
              }
              feature.setStyle(style);
            });
            let vectorTemp = new ol.layer.Vector({
              source: new ol.source.Vector({
                features: geometryTemp
              })
            });
            let nameLabel = $filter('translate')("hpo.admin.dashBoardFeedBack."+name+".label");
            let descriptionLabel = $filter('translate')("hpo.admin.dashBoardFeedBack."+name+".description");
            layersDefiniton.push({
              "name": nameLabel.startsWith("hpo.admin.dashBoardFeedBack")?name:nameLabel,
              "description": descriptionLabel.startsWith("hpo.admin.dashBoardFeedBack")?name:descriptionLabel,
              "visible": visible,
              "point": type === 'Point' || type === 'MultiPoint',
              "color": color,
              "count": features[name].count,
              "length": features[name].length === 0 ? "" : features[name].length,
              "vector": vectorTemp
            });
            if(visible){
              layers.push(vectorTemp);
            }
            return geometryTemp;
          }
      },
    };
  };

  dashboardHpoEnrichment.$inject = [
    'HpoCarteAppFactory',
    'HpoDataVisServices',
    'FeatureTypeFactory',
    'HpoAppServices',
    'gaDomUtils',
    '$q',
    '$rootScope',
    '$filter',
    'gcMapUtils'
  ];
  return dashboardHpoEnrichment;
});
function generateStyle(type, style, color) {
  if (type === 'Point' || type === 'MultiPoint') {
    style = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 3,
        fill: new ol.style.Fill({
          color: color
        }),
      }),
    });
  } else if (type === 'Line' || type === 'MultiLine' ||
    type === 'LineString' || type === 'MultiLineString') {
    style = new ol.style.Style({
      stroke: new ol.style.Stroke({ color: color, width: 1 })
    });
  } else {
    style = new ol.style.Style({
      stroke: new ol.style.Stroke({ color: color}),
      fill: new ol.style.Fill({
        color: color
      })
    });
  }
  return style;
}

