'use strict';
define(function() {
  var sldpolygonsymbolizer = function($filter, x2js, sldUtils, $rootScope) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/style/views/symbolizer/sldpolygonsymbolizer.html',
      restrict: 'A',
      scope: {
        component: '=component',
        fti: '=fti',
        rules: '=rules',
        ruletypepossibilities: '=ruletypepossibilities',
        selectsymbol: '=selectsymbol',
        selectedcomponent: '= selectedcomponent',
        _uom:'=',
        isannotation: '=?'
      },
      link: function(scope, elt, attrs, ctrl) {
        if (attrs['usehash'] != null)
          scope.usehash = attrs['usehash'] == 'true';
        else scope.usehash = false;

        scope.hashtemplates = [];
        if (scope.usehash) {
          for (var i in ol.style.FillPattern.prototype.patterns) {
            var p = new ol.style.FillPattern({ pattern: i });
            var template = {
              title: i,
              pattern: p,
              image: 'url("' + p.getImage().toDataURL() + '")',
            };

            scope.hashtemplates.push(template);

            if (scope.component) {
              if (scope.component.hashtemplate != null) {
                if (scope.component.hashtemplate == template.title)
                  scope.selectedHashBgrd = template.image;
              }
            }
          }

          if (scope.component) {
            if (scope.component.hashtemplate == null) {
              scope.component.hashtemplate =
                ol.style.FillPattern.prototype.patterns[i];
              scope.selectedHashBgrd = scope.hashtemplates[0].image;
            }
          }
        }

        //console.log(scope.component.Fill);
        scope.polygonType = sldUtils.getSubTypeOfSymbolizer(
          'POLYGON',
          scope.component
        );
        //scope.polygonType = sldUtils.getSubTypeOfSymbolizer('POINT', scope.component);
        scope.selectedComponent = { index: 0 };
        scope.component._uom='';
        /*scope.selectRule = {
                    type : 'rule',
                    rule : [scope.selectsymbol.symbol],
                    symbolizerName : scope.selectsymbol.type
                }*/

        // var sldService = sldServiceFactory.getInstance();

        // ------------
        // SIMPLE POLYGON
        // ------------
        /* scope.fillTypes = [
                     { key : 'continuous', label : 'Continuous' },
                     { key : 'grid', label : 'Grid' }
                 ];

                 scope.fillType = 'continuous';*/
        // var wellKnownName = sldService.getSubObj('Fill.GraphicFill.Graphic.Mark.WellKnownName', scope.component);
        // if(wellKnownName=='shape://times') scope.fillType = 'grid';

        function getCssParameterByName(cssParameters, hitParamName) {
          for (var i in cssParameters) {
            var cssParam = cssParameters[i];
            if (hitParamName === cssParam._name) return cssParam;
          }

          return null;
        }

        scope.selectHashTemplate = function(hashtemplate) {
          scope.component.hashtemplate = hashtemplate.title;
          scope.selectedHashBgrd = hashtemplate.image;
        };

        scope.setFillType = function() {
          switch (scope.fillType) {
            case 'continuous':
              var xml = '<CssParameter name="fill">#000000</CssParameter>';
              break;

            case 'grid':
              var xml =
                '<GraphicFill>' +
                '<Graphic>' +
                '<Mark>' +
                '<WellKnownName>shape://times</WellKnownName>' +
                '<Stroke>' +
                '<CssParameter name="stroke">#000000</CssParameter>' +
                '<CssParameter name="stroke-width">1</CssParameter>' +
                '</Stroke>' +
                '</Mark>' +
                '</Graphic>' +
                '</GraphicFill>';

              break;
          }

          scope.component.Fill = x2js.xml_str2json(xml);
        };

        // define stroke type
        scope.stroke = {
          type: 'none',
          types: [
            {
              key: 'none',
              label: 'model.styles.editor.symbolizers.common.stroke.types.none',
            },
            {
              key: 'continuous',
              label:
                'model.styles.editor.symbolizers.common.stroke.types.continuous',
            },
            {
              key: 'dash',
              label: 'model.styles.editor.symbolizers.common.stroke.types.dash',
            },
            {
              key: 'dots',
              label: 'model.styles.editor.symbolizers.common.stroke.types.dots',
            },
          ],
        };

        if (scope.selectedcomponent) {
          /**
           * When the user select another rule
           */
          scope.$watch(
            function() {
              var index0 = scope.selectedcomponent.index;
              var lastIndex = parseInt(index0.charAt(index0.length - 1));
              var firstIndex = parseInt(index0.charAt(0));
              scope.selectedComponent.index = lastIndex;
              //return scope.rules[scope.selectedComponent.index]
              return scope.rules[firstIndex][scope.selectsymbol.type][
                scope.selectedComponent.index
              ];
            },
            function(symbol) {
              if (symbol) {
                //scope.component.symbolType = sldUtils.getSubTypeOfSymbolizer(scope.selectRule.symbolizerName, symbol);
                //console.log(scope.selectRule);
                scope.component.symbolType = sldUtils.getSubTypeOfSymbolizer(
                  scope.selectsymbol.type,
                  symbol
                );
              }
            }
          );
        }

        /**
         * switchRuleSymbolType
         */
        scope.switchRuleSymbolType = function() {
          console.log(scope.component);
          var index0 = scope.selectedcomponent.index;
          var lastIndex = parseInt(index0.charAt(index0.length - 1));
          var firstIndex = parseInt(index0.charAt(0));
          scope.selectedComponent.index = lastIndex;
          sldUtils
            .switchRuleSymbolType(scope.component.symbolType)
            .then(function(newRule) {
              scope.rules[firstIndex][scope.selectsymbol.type][
                scope.selectedComponent.index
              ] = newRule[scope.selectsymbol.type][0];
              scope.polygonType = scope.component.symbolType;
              var data = {
                index: lastIndex,
                rule: 0,
                type: 'PolygonSymbolizer',
              };

              var component = scope.component;
              $rootScope.$broadcast('refresh_selected_component', {
                coord: data,
                cmp: component,
              });
            });
        };

        // used to retrieve the stroke type when user toggles between different point symboilizers
        scope.$watch(
          'component',
          function(component) {
            if (angular.isDefined(component.Stroke)) {
              var dashArray = $filter('cssParam')(
                scope.component.Stroke,
                'stroke-dasharray'
              )['__text'];
              if (dashArray && dashArray != '') {
                scope.stroke.type = 'dash';
                if (dashArray == '1 2') scope.strokeType = 'dots';
              } else {
                scope.stroke.type = 'continuous';
              }
            } else {
              scope.stroke.type = 'none';
            }            
            scope.component.componentShowHide = component.hasOwnProperty('textValue')?false:true;
          },
          1
        );

        scope.changeStrokeType = function() {
          if (scope.stroke.type == 'none') {
            delete scope.component.Stroke;
          } else {
            if (!angular.isDefined(scope.component.Stroke)) {
              scope.component.Stroke = {
                CssParameter: [
                  {
                    _name: 'stroke',
                    __text: '#000000',
                  },
                ],
              };
            }
            if (scope.stroke.type == 'dash') {
              $filter('cssParam')(scope.component.Stroke, 'stroke-dasharray')[
                '__text'
              ] = '4 2';
            } else if (scope.stroke.type == 'dots') {
              $filter('cssParam')(scope.component.Stroke, 'stroke-dasharray')[
                '__text'
              ] = '1 2';
            } else if (scope.stroke.type == 'continuous') {
              $filter('cssParam')(scope.component.Stroke, 'stroke-dasharray')[
                '__text'
              ] = '';
            }
          }
        };

        scope.$watch('component.noColorFill', function(cf) {
          scope.changeFillType();
        });

        //scope.component.noColorFill = false ;
        scope.changeFillType = function() {
          if (scope.component.noColorFill == 'true') {
            scope.component.noColorFill = true;
          }
          if (
            scope.component.noColorFill == true ||
            scope.component.noColorFill == 'true'
          ) {
            if (scope.usehash)
              getCssParameterByName(
                scope.component.Fill.CssParameter,
                'fill'
              ).__text = null;
            else delete scope.component.Fill;
          } else {
            if (!angular.isDefined(scope.component.Fill)) {
              if (scope.usehash)
                getCssParameterByName(
                  scope.component.Fill.CssParameter,
                  'fill'
                ).__text = '#000000';
              else
                scope.component.Fill = {
                  CssParameter: [
                    {
                      _name: 'fill',
                      __text: '#000000',
                    },
                  ],
                };
            }
          }
        };

        scope.lineJoinOptions = [
          {
            key: 'round',
            label: 'model.styles.editor.symbolizers.line.linejoin.round',
          },
          {
            key: 'bevel',
            label: 'model.styles.editor.symbolizers.line.linejoin.bevel',
          },
          {
            key: 'miter',
            label: 'model.styles.editor.symbolizers.line.linejoin.miter',
          },
        ];

        // ------------
        // LINE POLYGONS
        // ------------
        scope.lineShapes = [
          {
            key: 'shape://vertline',
            symbol: '| ',
            label: 'model.styles.editor.symbolizers.polygon.line.vertical',
          },
          {
            key: 'shape://horline',
            symbol: '_ ',
            label: 'model.styles.editor.symbolizers.polygon.line.horizontal',
          },
          {
            key: 'shape://slash',
            symbol: '/ ',
            label: 'model.styles.editor.symbolizers.polygon.line.slash',
          },
          {
            key: 'shape://backslash',
            symbol: '\\ ',
            label: 'model.styles.editor.symbolizers.polygon.line.backslash',
          },
          /*{ key : 'shape://dot', label : '. Dot' },*/
          {
            key: 'shape://plus',
            symbol: '+ ',
            label: 'model.styles.editor.symbolizers.polygon.line.plus',
          },
          {
            key: 'shape://times',
            symbol: 'x ',
            label: 'model.styles.editor.symbolizers.polygon.line.times',
          },

          /*{ key : 'shape://oarrow', label : '> Open Arrow' },
                    { key : 'shape://carrow', label : '▷ Closed Arrow' },*/
        ];

        // ------------
        // POLYGON LINES
        // ------------
      },
    };
  };

  sldpolygonsymbolizer.$inject = ['$filter', 'x2js', 'sldUtils', '$rootScope'];
  return sldpolygonsymbolizer;
});
