'use strict';
define(function() {
  var profilewidget = function (
    $rootScope,
    $filter,
    gaDomUtils,
    ngDialog,
    LongitudinalProfileFactory,
    ConfigFactory,
    FeatureTypeFactory,
    NetworkFactory,
    GoogleMapsFactory,
    AssEditProcessServices
  ) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/longitudinalprofile/views/longitudinalprofilewidget.html',
      restrict: 'A',
      link: function (scope, elt, attrs, ctrl) {
        let map = scope.map;
        scope.selectTool = {
          map: scope.map,
          uids: [],
        };
        scope.config = {};
        scope.diameters = [
          {
            divider: 1,
            name: 'm',
            alias: $filter('translate')('profil.config.diameterUnits.meter'),
          },
          {
            divider: 100,
            name: 'cm',
            alias: $filter('translate')(
              'profil.config.diameterUnits.centimeter'
            ),
          },
          {
            divider: 1000,
            name: 'mm',
            alias: $filter('translate')(
              'profil.config.diameterUnits.milimeter'
            ),
          },
        ];

        let apiMapping = {'ign':'IGN','google':'Google','openroute':'OpenRoute','':undefined}

        scope.apisAvailable = [];

        if($rootScope.xgos.portal.parameters.apikey){
          if($rootScope.xgos.portal.parameters.apikey.ign){
            scope.apisAvailable.push({name:'ign', alias:apiMapping['ign']})
          }
          if($rootScope.xgos.portal.parameters.apikey.google){
            scope.apisAvailable.push({name:'google', alias:apiMapping['google']})
          }
          if($rootScope.xgos.portal.parameters.apikey.openroute){
            scope.apisAvailable.push({name:'openroute', alias:apiMapping['openroute']})
          }
        }


        //Données de configuration pour le composant de  parcours reseau
        scope.config.network = '';
        scope.config.minnodes = 10;
        scope.config.maxnodes = 100;
        scope.config.nodesincr = 10;
        scope.config.elevationOption = 'BD';

        //Données de configuration pour le profil en long
        scope.config.edges = [
          { layeruid: '', zAmont: '', zAval: '', diameter: '' },
        ];
        scope.config.nodes = [
          { layeruid: '', zn: '', zr: '', attLabelNode: '' },
        ];
        scope.config.otherLayerElements = [];
        scope.config.elevationFactor = 1;

        scope.styleKeysElements = [
          { value: 'x', label: '<i class="fa fa-times"></i>' },
          { value: 'cross', label: '<i class="fa fa-plus"></i>' },
          { value: 'star', label: '<i class="fa fa-star"></i>' },
          {
            value: 'triangle',
            label: '<i class="fa fa-sort-asc"></i>',
          },
          { value: 'square', label: '<i class="fa fa-square"></i>' },
        ];

        //////////////////////////////////////////////////////////////
        // Gestion de la configuration
        /////////////////////////////////////////////////////////////
        function isFeatureLine(ft) {
          return ft.typeInfo == 'LINE';
        }
        function isFeaturePoint(ft) {
          return ft.typeInfo == 'POINT';
        }

        //Récupération des réseaux configurés dans le portail de l'application

        if (NetworkFactory.resources.networks.length > 0) {
          scope.networks = NetworkFactory.resources.networks;
        } else {
          // KIS-3378: Compense la mauvaise valeur par défaut de NetworkFactory.get
          NetworkFactory.get(false).then(
            () => {
              scope.networks = NetworkFactory.resources.networks;
            },
            (error) => {
              var errorMsg = error;
            }
          );
        }

        if (FeatureTypeFactory.resources.featuretypes.length > 0) {
          scope.features = FeatureTypeFactory.resources.featuretypes;
        } else {
          FeatureTypeFactory.get().then(() => {
            scope.features = FeatureTypeFactory.resources.featuretypes;
          });
        }

        if (FeatureTypeFactory.resources.featuretypes.length > 0) {
          scope.featuresLines = FeatureTypeFactory.resources.featuretypes.filter(
            isFeatureLine
          );
        } else {
          FeatureTypeFactory.get().then(() => {
            scope.featuresLines = FeatureTypeFactory.resources.featuretypes.filter(
              isFeatureLine
            );
          });
        }

        if (FeatureTypeFactory.resources.featuretypes.length > 0) {
          scope.featuresPoints = FeatureTypeFactory.resources.featuretypes.filter(
            isFeaturePoint
          );
        } else {
          FeatureTypeFactory.get().then(() => {
            scope.featuresPoints = FeatureTypeFactory.resources.featuretypes.filter(
              isFeaturePoint
            );
          });
        }

        scope.edgesAttributes = [];
        scope.addEdgeLayer = () => {
          scope.config.edges.push({
            layeruid: '',
            zAmont: '',
            zAval: '',
          });
        };
        scope.removeEdge = (edgeIndex) => {
          scope.config.edges.splice(edgeIndex, 1);
        };

        scope.getEdgeFeatureAttributes = (featureTypeUid, edgeIndex) => {
          if (featureTypeUid == null) return;
          for (let i = 0; i < scope.features.length; i++) {
            if (scope.features[i].uid == featureTypeUid) {
              scope.edgesAttributes[edgeIndex] = scope.features[i].attributes;
              break;
            }
          }
        };

        scope.nodesAttributes = [];
        scope.addNodeLayer = () => {
          scope.config.nodes.push({
            layeruid: '',
            zn: '',
            style: undefined,
          });
        };
        scope.removeNode = (edgeIndex) => {
          scope.config.nodes.splice(edgeIndex, 1);
        };

        scope.getNodeFeatureAttributes = (featureTypeUid, nodeIndex) => {
          if (featureTypeUid == null) return;
          for (let i = 0; i < scope.features.length; i++) {
            if (scope.features[i].uid == featureTypeUid) {
              scope.nodesAttributes[nodeIndex] = scope.features[i].attributes;
              break;
            }
          }
        };

        scope.addElementLayer = function () {
          scope.config.otherLayerElements.push({ layeruid: '' });
        };
        scope.removeElementLayer = (index) => {
          scope.config.otherLayerElements.splice(index, 1);
        };

        scope.onElementLayerChange = (element) => {
          for (let i = 0; i < scope.features.length; i++) {
            if (scope.features[i].uid == element.layeruid) {
              element.layerName = scope.features[i].name;
              break;
            }
          }
        };

        /**
         * Lit les données depuis la configuration.
         * @returns {undefined}
         */
        scope.readConfig = () => {
          //KIS-1112
          if (
            scope.config.otherLayerElements &&
            scope.config.otherLayerElements.length > 0
          ) {
            for (const element of scope.config.otherLayerElements) {
              element.displayOnProfile = element.checkByDefault;
            }
          }
        };

        /**
         * Récupère et charge  la configuration depuis le fichier.
         * @returns {undefined}
         */

        scope.getConfig = () => {
          ConfigFactory.get('widgets', 'longitudinalprofileconfig').then(
            (res) => {
              if (res.data != '') {
                  scope.config.diameter = res.data.diameter
                    ? res.data.diameter
                    : scope.diameters[3];
                if (scope.config.network != null &&
                  scope.config.network != '' &&
                  res.data.network != scope.config.network
                ) {
                  initialiseTheConf();
                } else {
                  scope.config = checkAndUpdateTheConf(res.data);
                }
                console.info('Configuration de longitudinalprofile chargée.');
              } else {
                if (scope.config.network != null && scope.config.network != '') {
                  scope.config.diameter = scope.diameters[3];
                  initialiseTheConf();
                }
              }
              scope.readConfig();
            },
            (reason) => {
              console.error(
                'Configuration de longitudinalprofile non chargée:' + reason
              );
            }
          );
        };

        let initialiseTheConf = () => {
          if (scope.networks){
            let network = scope.networks.filter(
                (net) => net.name === scope.config.network
            )[0];
            scope.config.edges = [];
            network.edgesTypes.forEach((networkEdge) => {
              scope.config.edges.push({
                layeruid: networkEdge.ftiUID,
                zAmont: '',
                zAval: '',
                diameter: '',
              });
            });
            scope.config.nodes = [];
            network.nodesTypes.forEach((networkNode) => {
              scope.config.nodes.push({
                layeruid: networkNode.ftiUID,
                zn: '',
                zr: '',
                attLabelNode: '',
              });
            });
          }
        };

        let checkAndUpdateTheConf = (config) => {
          if (scope.networks){
            let network = scope.networks.filter(
                (net) => net.name === config.network
            )[0];
            network.edgesTypes.forEach((networkEdge) => {
              if (
                  config.edges.filter((edge) => edge.layeruid === networkEdge.ftiUID)
                      .length === 0
              ) {
                config.edges.push({
                  layeruid: networkEdge.ftiUID,
                  zAmont: '',
                  zAval: '',
                  diameter: '',
                });
              }
            });
            network.nodesTypes.forEach((networkNode) => {
              if (
                  config.nodes.filter(
                      (nodes) => nodes.layeruid === networkNode.ftiUID
                  ).length === 0
              ) {
                config.nodes.push({
                  layeruid: networkNode.ftiUID,
                  zn: '',
                  zr: '',
                  attLabelNode: '',
                });
              }
            });
            for (let node of network.nodesTypes) {
              scope.selectTool.uids.push(node.ftiUID);
            }
          }
          return config;
        };
        scope.$on('openTools_longitudinalprofilewidget',() => {
          scope.getConfig();
        });

        /**
         * Ouvre une fenetre de consultation et de modification de la configuration.
         * @returns {undefined}
         *
         */
        let ngDialogPromise;
        scope.openConfig = () => {
          ngDialogPromise = ngDialog.openConfirm({
            template:
              'js/XG/widgets/mapapp/longitudinalprofile/views/configuration.html',
            scope: scope,
            className: 'ngdialog-theme-plain width800 nopadding miniclose',
          });
          ngDialogPromise.then(
            (data) => {
              scope.saveconfig();
              require('toastr').info(data);
            },
            (data) => {
              scope.getConfig();
              require('toastr').info(data);
            }
          );
        };

        /**
         * Sauve la configuration dans le fichier.
         * @returns {undefined}
         */
        scope.saveconfig = () => {
          ConfigFactory.add(
            scope.config,
            'widgets',
            'longitudinalprofileconfig'
          ).then(
            (res) => {
              scope.readConfig();
              require('toastr').success(res.data);
            },
            (reason) => {
              require('toastr').error(reason);
            }
          );
        };

        //////////////////////////////////////////////////////////////
        // FIN Gestion de la configuration
        /////////////////////////////////////////////////////////////

        //Service d'obtention de l'élevation terrain de google
        if(scope.config.apiToUse == 'google'){
          GoogleMapsFactory.lazyLoad().then(() => { });
        }
        const wgs84Sphere = new ol.Sphere(6378137);
        let elevationResults = [];

        /**
         * Récupére les coordonées de la feature line passé en argument
         * TODO: Interpoler les points situés entre les sommets afin d'avoir une succession de points equidistants et assez rapprochés.
         * @param {type} simpleLine
         * @returns {undefined}
         */
        function getCoordinatesFromFeatureLine(featuresLine, previousPoint) {
          let coords = [];
          let isReverse = false;

          const line = featuresLine.geometry;
          if (line.type == 'LineString') {
            coords = coords.concat(line.coordinates);
          } else if (line.type == 'MultiLineString') {
            angular.forEach(line.coordinates, (subCoords, key) => {
              coords = coords.concat(subCoords);
            });
          }
          let prevPointCoord = undefined;
          if (previousPoint) {
            if (previousPoint.type == 'Point') {
              prevPointCoord = previousPoint.geometry.coordinates;
              const firstLinePointCoord = coords[0];
              const lastLinePointCoord = coords[coords.length - 1];
              if (
                Math.ceil(prevPointCoord[0] * 100) ==
                Math.ceil(firstLinePointCoord[0] * 100) &&
                Math.ceil(prevPointCoord[1] * 100) ==
                Math.ceil(firstLinePointCoord[1] * 100)
              ) {
                isReverse = false;
              } else if (
                Math.ceil(prevPointCoord[0] * 100) ==
                Math.ceil(lastLinePointCoord[0] * 100) &&
                Math.ceil(prevPointCoord[1] * 100) ==
                Math.ceil(lastLinePointCoord[1] * 100)
              ) {
                isReverse = true;
              } else {
                isReverse = false;
              }
            }
          }

          if (isReverse) {
            const reverseCoords = [];
            for (let i = coords.length - 1; i <= 0; i--) {
              reverseCoords.push(coords[i]);
            }
            return reverseCoords;
          }

          return coords;
        }

        /**
         * Récupére les points du parcours à partir desquels on demandera l'elevation terrain correspondante.
         * On récupère chaque sommet de chaque objet linéaire du parcours
         * @returns {undefined}
         */
        function getSourceCoordinatesForElevation() {
          //Features du parcours réseau
          const featuresPath = scope.lastDPath.featureCollectionData.features;
          //Coordonnées des points dont on calculera l'élevation
          let pathCoordinates = [];
          //Pour chaque objet linéaire du parcours (1 sur 2), on récupére les coordonnées de ses vertex.
          for (let i = 1; i < featuresPath.length; i = i + 2) {
            //On retire le dernier vertex du tableau pour éviter qu'il ne fasse doublons avec le premier vertex de la feature ligne qui vient.
            if (i != 1) {
              pathCoordinates.splice(pathCoordinates.length - 1, 1);
            }
            //récupérer le point (feature index i-1) et vérifier si le 1er point de la ligne intersecte ce point sinon : boolean reverse = true;
            const prevPoint = featuresPath[i - 1];
            //On ajoute au tableau des vertices les vertex de la featureLine courante
            pathCoordinates = pathCoordinates.concat(
              getCoordinatesFromFeatureLine(featuresPath[i], prevPoint)
            );
          }
          return pathCoordinates;
        }

        /**
         * Calcule les distances entre les points du tableau de coordonnées passé en argument.
         * @param {type} coordinates
         * @returns {Array}
         */
        //                function getdistanceCoordinatesForElevation(coordinates){
        //                    var distances = [];
        //
        //                    distances.push(0)
        //                    for (var i = 1; i < coordinates.length; i++) {
        //                        var d =  wgs84Sphere.haversineDistance(ol.proj.transform(coordinates[i-1], map.getView().getProjection(), 'EPSG:4326'),
        //                                    ol.proj.transform(coordinates[i], map.getView().getProjection(), 'EPSG:4326'));
        //                        distances.push(d);
        //                    }
        //
        //                     return distances;
        //                }

        /**
         * Récupère l'élevation des points vertex des features linéaires du parcours
         * @returns {undefined}
         */
        let getElevation = () => {
          const coordinates = getSourceCoordinatesForElevation();
          //distancesTerrain = getdistanceCoordinatesForElevation(coordinates);

          //  transform into lat lng
          const coordinatesLatLng = [];
          for (let i = 0; i < coordinates.length; i++) {
            coordinatesLatLng.push(
              GoogleMapsFactory.coordinatesToLatLng(
                coordinates[i],
                map.getView().getProjection(),
                scope.config.apiToUse != 'google'
              )
            );
          }

          if(scope.config.apiToUse == 'google'){
            GoogleMapsFactory.lazyLoad().then(() => { });
            new google.maps.ElevationService().getElevationForLocations(
              {
                locations: coordinatesLatLng,
              },
              (results, status) => {
                if (status == google.maps.ElevationStatus.OK) {
                  elevationResults = results.map((r) => {
                    return Math.round(r.elevation * 100) / 100;
                  });
                } else {
                  require('toastr').warning('Unable to get elevation values');
                  elevationResults = [];
                }
              }
            );
          }else{
            elevationResults = [];
          }
        };

        //Paramètres pour la requete serveur des features representant le profil
        scope.param = {};
        scope.param.elevation = elevationResults;
        scope.param.path = [];
        scope.param.nodesid = '99f14c1e-55b4-4083-97d3-ddf18e368fa6';
        scope.param.edgesid = 'a65cabf0-5c1c-485f-84de-4ecf4c43071f';
        scope.param.attZAmont = 'ZA';
        scope.param.attZAval = 'ZAV';
        scope.param.srid = '';
        scope.param.facteurz = 100.0;

        // Data correspondant au path
        scope.lastDPath = {};

        /**
         * Exécutée à la fin du parcours réseau.
         * @returns {undefined}
         */
        scope.lastDPathFound = () => {
          highLightPath();
          //var isElevationDone = false
          scope.param.path.splice(0);
          //console.log(scope.lastDPath);
          scope.lastDPath.featureCollectionData.features.forEach((f) => {
            console.log(f);
            const deleteIndex = scope.param.path
              .map((x) => {
                return x;
              })
              .indexOf(f.id);
            if (deleteIndex == -1) {
              scope.param.path.push(f.id);
            }
          });
          getEndsNodeId();
          getElevation();
          //juste afficher un markeur indiquant si le résulat de la requete d'élévation terrain de google a été recue.
        };

        scope.endsNodeIds = [];

        function getEndsNodeId (){
          const lastIndex = scope.lastDPath.featureCollectionData.features.length - 1;
          scope.endsNodeIds.push(scope.lastDPath.featureCollectionData.features[0].properties.id);
          scope.endsNodeIds.push(
            scope.lastDPath.featureCollectionData.features[lastIndex].properties
              .id
          );
        }

        /// GESTION DE LA MISE EN EVIDENCE DU PARCOURS /////////////////

        const format = new ol.format.GeoJSON();
        const originSource = new ol.source.Vector({
          //create empty vector
        });

        const originLayer = new ol.layer.Vector({
          source: originSource,
          style: new ol.style.Style({
            image: new ol.style.Circle({
              radius: 8,
              fill: new ol.style.Fill({
                color: 'green',
              }),
              stroke: new ol.style.Stroke({
                color: 'green',
              }),
            }),
          }),
        });

        const pathsSource = new ol.source.Vector({
          //create empty vector
        });

        const pathsLayer = new ol.layer.Vector({
          source: pathsSource,
          style: new ol.style.Style({
            stroke: new ol.style.Stroke({
              color: 'red',
              lineDash: [4],
              width: 4,
            }),
            fill: new ol.style.Fill({
              color: 'red',
            }),
          }),
        });

        function highLightPath() {
          map.addLayer(pathsLayer);
          map.addLayer(originLayer);

          const features = format.readFeatures(
            scope.lastDPath.featureCollectionData
          );
          originSource.addFeature(features[0]);

          for (let i = 1; i < features.length; i++) {
            pathsSource.addFeature(features[i]);
          }
        }

        /// FIN GESTION DE LA MISE EN EVIDENCE DU PARCOURS /////////////////

        /**
         * Ouverture de la popup de visualisation du profile.
         * @returns {undefined}
         */

        scope.isEsriType = false;

        scope.openprofile = () => {
          if (scope.param.path.length == 0) {
            require('toastr').warning($filter('translate')('profil.config.alert.selectObjects'));
            return;
          }
          if (!scope.config.diameter) {
            require('toastr').warning($filter('translate')('profil.config.alert.noDiameter'))
            return;
          }
          gaDomUtils.showGlobalLoader();
          scope.param.nodesList = scope.config.nodes;

          scope.param.edgesList = scope.config.edges;

          scope.param.otherLayerElements = scope.config.otherLayerElements;
          scope.param.srid = '';
          scope.param.facteurz = scope.config.elevationFactor;
          scope.param.elevationOption = scope.config.elevationOption;
          scope.param.elevations = elevationResults;
          scope.param.diameter = scope.config.diameter;
          scope.param.apiToUse = scope.config.apiToUse;

          LongitudinalProfileFactory.get(scope.param)
            .then((res) => {
              if (res.data == '') {
                require('toastr').error('Pas de résultat de profil en long.');
                return;
              }
              scope.geojsondata = res.data;
              scope.elementConfigs = [];
              if (scope.config.otherLayerElements.length > 0) {
                for (const element of scope.config.otherLayerElements) {
                  if (element.displayOnProfile) {
                    scope.elementConfigs.push(element);
                  }
                }
              }
              let fuid = null;
              if (scope.param.edgesList.length > 0) {
                fuid = scope.param.edgesList[0].layeruid
              }
              LongitudinalProfileFactory.isEsriType(fuid)
                .then((res) => {
                  scope.isEsriType = res.data;
                  scope.apiToUseFromElevation = apiMapping[scope.config.elevationOption !== 'BD' 
                                                && scope.config.apiToUse?scope.config.apiToUse:''];
                  //KIS-1112
                  //scope.elementConfigs = scope.config.otherLayerElements;
                  scope.popupProfil = ngDialog.open({
                    template:
                      'js/XG/widgets/mapapp/longitudinalprofile/views/modal.profil.html',
                    className:
                      'ngdialog-theme-plain width1000 nopadding miniclose',
                    closeByDocument: false,
                    scope: scope,
                  });
                })
                .catch((reason) => {
                  require('toastr').error(reason);
                  console.error(reason);
                });
            })
            .catch((reason) => {
              require('toastr').error(reason);
              console.error(reason);
            })
            .finally(() => {
              gaDomUtils.hideGlobalLoader();
            });
        };

        //                var geoJsonTest = {"type":"FeatureCollection","totalFeatures":32,"features":[{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,72],[0,-120]]},"properties":{"type":"array"},"id":"array.tabV_0"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[350.41,56],[350.41,-120]]},"properties":{"type":"array"},"id":"array.tabV_1"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,-20],[350.41,-20]]},"properties":{"type":"array"},"id":"array.tabh_1"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,-40],[350.41,-40]]},"properties":{"type":"array"},"id":"array.tabh_2"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,-60],[350.41,-60]]},"properties":{"type":"array"},"id":"array.tabh_3"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,-80],[350.41,-80]]},"properties":{"type":"array"},"id":"array.tabh_4"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,-100],[350.41,-100]]},"properties":{"type":"array"},"id":"array.tabh_5"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,-120],[350.41,-120]]},"properties":{"type":"array"},"id":"array.tabh_6"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[350.41,0]]},"properties":{"type":"axe"},"id":"axe.Axe X"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,0],[0,72]]},"properties":{"type":"axe"},"id":"axe.Axe Y"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,72],[350.41,56]]},"properties":{"type":"cana"},"id":"edge.0"},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[0,62.4],[44.3176,62.6024],[84.5976,62.7863],[121.9936,62.957],[157.6592,63.1199],[192.748,63.2801],[228.4136,63.443],[265.8096,63.6137],[306.0896,63.7976],[350.4072,64]]},"properties":{"type":"terrain"},"id":"ground.terrain"},{"type":"Feature","geometry":{"type":"Point","coordinates":[322.5064,57.2741]},"properties":{"id":"PIPES.76139","X":488032.32654153317,"Y":1278579.7854493593,"type":"intersectedFeature","layerName":"PIPES","elevation":null,"distance":null},"id":"intersectedFeature.PIPES.76139"},{"type":"Feature","geometry":{"type":"Point","coordinates":[350.4071,56.0001]},"properties":{"id":"PIPES.77716","X":488035.68027321727,"Y":1278552.1019770924,"type":"intersectedFeature","layerName":"PIPES","elevation":null,"distance":null},"id":"intersectedFeature.PIPES.77716"},{"type":"Feature","geometry":{"type":"Point","coordinates":[242.0734,60.9467]},"properties":{"id":"PIPES.77889","X":488022.63790043653,"Y":1278659.749113919,"type":"intersectedFeature","layerName":"PIPES","elevation":null,"distance":null},"id":"intersectedFeature.PIPES.77889"},{"type":"Feature","geometry":{"type":"Point","coordinates":[-100,0]},"properties":{"label":"Terrain","type":"labelvSurface"},"id":"label.labelvSurface"},{"type":"Feature","geometry":{"type":"Point","coordinates":[175.205,-80]},"properties":{"label":"20.0","type":"labelvcentered"},"id":"label.labelv_Diameter_CONNECTIONS.23"},{"type":"Feature","geometry":{"type":"Point","coordinates":[-100,-80]},"properties":{"label":"Diametre","type":"labelvLegend"},"id":"label.labelv_Diametre"},{"type":"Feature","geometry":{"type":"Point","coordinates":[-100,-120]},"properties":{"label":"Distance Cumulé","type":"labelvLegend"},"id":"label.labelv_Distance_Cumulee"},{"type":"Feature","geometry":{"type":"Point","coordinates":[-100,-100]},"properties":{"label":"Distance partielle","type":"labelvLegend"},"id":"label.labelv_Distance_Partielle"},{"type":"Feature","geometry":{"type":"Point","coordinates":[-100,-60]},"properties":{"label":"Pente %","type":"labelvLegend"},"id":"label.labelv_Pente"},{"type":"Feature","geometry":{"type":"Point","coordinates":[175.205,-60]},"properties":{"label":"1.15","type":"labelvcentered"},"id":"label.labelv_Pente_CONNECTIONS.23"},{"type":"Feature","geometry":{"type":"Point","coordinates":[-100,-40]},"properties":{"label":"Cote Radier","type":"labelvLegend"},"id":"label.labelv_Radier"},{"type":"Feature","geometry":{"type":"Point","coordinates":[-100,-20]},"properties":{"label":"Cote Tampon","type":"labelvLegend"},"id":"label.labelv_Tampon"},{"type":"Feature","geometry":{"type":"Point","coordinates":[175.205,-120]},"properties":{"label":"350.41","type":"labelvcentered"},"id":"label.labelv_distanceCumulee_1"},{"type":"Feature","geometry":{"type":"Point","coordinates":[175.205,-100]},"properties":{"label":"350.41","type":"labelvcentered"},"id":"label.labelv_distancePartielle_1"},{"type":"Feature","geometry":{"type":"Point","coordinates":[350.41,-40]},"properties":{"label":"14.0","type":"labelv"},"id":"label.labelv_radier_AIR_VALVES.167"},{"type":"Feature","geometry":{"type":"Point","coordinates":[0,-40]},"properties":{"label":"18.0","type":"labelv"},"id":"label.labelv_radier_AIR_VALVES.237"},{"type":"Feature","geometry":{"type":"Point","coordinates":[350.41,-20]},"properties":{"label":"16.0","type":"labelv"},"id":"label.labelv_tampon_AIR_VALVES.167"},{"type":"Feature","geometry":{"type":"Point","coordinates":[0,-20]},"properties":{"label":"20.0","type":"labelv"},"id":"label.labelv_tampon_AIR_VALVES.237"},{"type":"Feature","geometry":{"type":"Point","coordinates":[0,72]},"properties":{"X":487993.05242944753,"Y":1278899.7712610366,"elevation":72,"distance":0,"id":"AIR_VALVES.237","type":"terrain_point"},"id":"vertex.0"},{"type":"Feature","geometry":{"type":"Point","coordinates":[350.41,56]},"properties":{"X":488035.1837940449,"Y":1278552.046717161,"elevation":56,"distance":350.41,"id":"AIR_VALVES.167","type":"terrain_point"},"id":"vertex.1"}]};
        //                scope.openprofile = function(){
        //                    scope.geojsondata = geoJsonTest;
        //                    scope.elementConfigs = scope.config.otherLayerElements;
        //
        //                    ngDialog.open({
        //                        template: 'js/XG/widgets/mapapp/longitudinalprofile/views/modal.profil.html',
        //                        className: 'ngdialog-theme-plain fullScreen nopadding miniclose',
        //                        closeByDocument: false,
        //                        scope: scope
        //                    });
        //                };

        scope.reset = () => {
          scope.param.path.splice(0);
          originSource.clear();
          pathsSource.clear();
          map.removeLayer(pathsLayer);
          map.removeLayer(originLayer);
          scope.endsNodeIds = [];
        };

        // receive exportDXF button's click from profilPreview
        $rootScope.$on('openDxfPopup', function (event, args) {
          scope.popupProfil.close();
          AssEditProcessServices.longitudinalProfil(scope);
        });
      }, //link
    };
  };
  profilewidget.$inject = [
    '$rootScope',
    '$filter',
    'gaDomUtils',
    'ngDialog',
    'LongitudinalProfileFactory',
    'ConfigFactory',
    'FeatureTypeFactory',
    'NetworkFactory',
    'GoogleMapsFactory',
    'AssEditProcessServices',
  ];
  return profilewidget;
});
