'use strict';
define(function() {
  var gcelement = function(NetworkFactory, $timeout, gcInteractions) {
    return {
      templateUrl: 'js/XG/widgets/utilities/network/views/gcnodeselect.html',
      restrict: 'A',
      scope: {
        map: '=map',
        netname: '=netname',
        nodetype: '@',
        deactivateAtFirstFoundNode: '@',
        pathprocessconfig: '=pathprocessconfig',
        result: '=res',
        state: '=',
        onactivated: '&',
        onfinish: '&',
        toolBarWidget: '=?toolbarwidget',
      },
      transclude: true,
      link: function(scope, element, attrs, ctrl) {
        var networkName = scope.netname;
        var pathProcessConfig = null;
        if (scope.pathprocessconfig)
          pathProcessConfig = simplifyPathProcessConfig(
            scope.pathprocessconfig
          );

        var map = scope.map;
        var inSrid = map
          .getView()
          .getProjection()
          .getCode();

        function ftypeAttributeValuesToSavePartConfig(fTypeAttributeValues) {
          var elements = [];

          for (var ftiUID in fTypeAttributeValues) {
            var fTypeAttributeValues = fTypeAttributeValues[ftiUID];

            var ftiElements = [];

            angular.forEach(fTypeAttributeValues, function(attributeValue) {
              var attributeFilter = {
                attrName: attributeValue.attributeName,
                value: attributeValue.res[attributeValue.attributeName],
              };

              ftiElements.push(attributeFilter);
            });

            elements.push({
              ftiUID: ftiUID,
              attributesFilters: ftiElements,
            });
          }
          return elements;
        }

        function isDeactivateAtFirstFoundeNode() {
          return (
            scope.deactivateAtFirstFoundNode != null &&
            scope.deactivateAtFirstFoundNode == 'true'
          );
        }

        function dataToSavePartConfig(data) {
          var fTypesUIDS = [];
          angular.forEach(data.leftData, function(choosedFType) {
            fTypesUIDS.push(choosedFType.uid);
          });

          return fTypesUIDS;
        }

        function simplifyPathProcessConfig(networkTool) {
          var networkToolConfig = {
            label: networkTool.label,
            toolType: networkTool.toolType,
            amontElements: [],
            avalElements: [],
            networkElements: [],
            amontElementsFilters: [],
            avalElementsFilters: [],
            networkElementsFilters: [],
          };

          var amontElementsConfigPart = dataToSavePartConfig(
            networkTool.amontElementsData
          );
          var avalElementsConfigPart = dataToSavePartConfig(
            networkTool.avalElementsData
          );
          var networkElementsConfigPart = dataToSavePartConfig(
            networkTool.edgesAndNodesData
          );

          networkToolConfig.amontElements = amontElementsConfigPart;
          networkToolConfig.avalElements = avalElementsConfigPart;
          networkToolConfig.networkElements = networkElementsConfigPart;

          var amontElementsFiltersConfigPart = ftypeAttributeValuesToSavePartConfig(
            networkTool.currentAmontEditFTypeAttributeValues
          );
          var avalElementsFiltersConfigPart = ftypeAttributeValuesToSavePartConfig(
            networkTool.currentAvalEditFTypeAttributeValues
          );
          var networkElementsFiltersConfigPart = ftypeAttributeValuesToSavePartConfig(
            networkTool.currentEditFTypeAttributeValues
          );

          networkToolConfig.amontElementsFilters = amontElementsFiltersConfigPart;
          networkToolConfig.avalElementsFilters = avalElementsFiltersConfigPart;
          networkToolConfig.networkElementsFilters = networkElementsFiltersConfigPart;

          return networkToolConfig;
        }

        function deactivate() {
          scope.isActive = false;
          //map.removeInteraction(scope.pointer);
          if (scope.networkSelectInteraction) {
            map.removeInteraction(scope.networkSelectInteraction);
            scope.networkSelectInteraction.setActive(false);
          }
        }

        function networkSelectStart(evt) {
          /*sketchFeature = evt.feature;*/
        }

        function networkSelectEnd(evt) {
          //scope.features = evt.feature;
          var format = new ol.format.GeoJSON();

          var feature = format.writeFeatureObject(evt.feature);
          //

          if (scope.radiomode) {
            scope.networkSelectInteraction.setActive(false);
            map.removeInteraction(scope.networkSelectInteraction);
          }

          scope.resgeometry = feature.geometry;
          var coordX = scope.resgeometry.coordinates[0];
          var coordY = scope.resgeometry.coordinates[1];

          if (scope.pathprocessconfig)
            pathProcessConfig = simplifyPathProcessConfig(
              scope.pathprocessconfig
            );

          NetworkFactory.getnearestnode(
            pathProcessConfig,
            networkName,
            inSrid,
            coordX,
            coordY,
            scope.nodetype
          ).then(function(res) {
            scope.result = res.data;
            console.log(scope.result);

            $timeout(scope.onfinish, 100);
            if (
              scope.result != null &&
              scope.result != '' &&
              isDeactivateAtFirstFoundeNode()
            )
              deactivate();
          });
        }

        function toggleActionLaunch() {
          if (
            scope.isActive &&
            scope.networkSelectInteraction &&
            scope.networkSelectInteraction.getActive()
          ) {
            scope.isActive = false;
            //map.removeInteraction(scope.pointer);
            if (scope.networkSelectInteraction) {
              scope.networkSelectInteraction.setActive(false);
              map.removeInteraction(scope.networkSelectInteraction);
            }

            //ajouter ce code si on veut enlever la sélection après la désactivation du tool
            //SelectManager.clear();
          } else {
            scope.isActive = true;
          }

          if (scope.isActive) {
            scope.networkSelectInteraction = new ol.interaction.Draw({
              type: 'Point',
            });

            scope.networkSelectInteraction.set('gctype', 'kis');
            scope.networkSelectInteraction.set('interaction', 'Draw');
            scope.networkSelectInteraction.set('widget', 'network');
            scope.networkSelectInteraction.setActive(true);
            gcInteractions.setCurrentToolBar(scope.toolBarWidget);
            map.addInteraction(scope.networkSelectInteraction);
            //on start
            scope.networkSelectInteraction.on('drawstart', networkSelectStart);

            // on end
            scope.networkSelectInteraction.on('drawend', networkSelectEnd);
          } else deactivate();
        }

        scope.selectNode = function(event) {
          console.log('go for select node');
          if (!scope.isActive) scope.onactivated();

          toggleActionLaunch();
        };

        scope.$watch('state', function(newVal, oldVal) {
          if (newVal == 'DEACTIVATED' && scope.isActive == true)
            toggleActionLaunch();
        });
      },
    };
  };

  gcelement.$inject = ['NetworkFactory', '$timeout', 'gcInteractions'];
  return gcelement;
});
