/*global define, CodeMirror */
define(['angular', 'toastr'], function(angular, toastr) {
  'use strict';

  /**
   * StyleCtrl Ctrl
   * @param $scope
   * @param FeatureTypeFactory
   * @param StyleFactory
   * @param $timeout
   * @param x2js
   * @param $filter
   * @param sldUtils
   * @constructor
   */
  var StyleCtrl = function(
    $scope,
    FeatureTypeFactory,
    StyleFactory,
    $timeout,
    x2js,
    $filter,
    sldUtils,
    gaJsUtils
  ) {
    $scope.codeEditor = null;
    var styleDialog;

    function getEditor() {
      if ($scope.codeEditor === null) {
        var elem = document.getElementById('style_sld');
        $scope.codeEditor = CodeMirror.fromTextArea(elem, {
          lineNumbers: true,
          mode: 'xml',
        });
      }
      return $scope.codeEditor;
    }

    /**
     * Create or update the style
     */
    $scope.editStyle = function() {
      var fromSLDEditor = getEditor()
        .getDoc()
        .getValue()
        .replace(/\n/g, '')
        .replace(/\t/g, '');

      if (StyleFactory.isValidSld(fromSLDEditor)) {
        styleDialog.close();
        if ($scope.isNewResource) {
          StyleFactory.add(fromSLDEditor, $scope.edit_resource.name).then(
            function() {
              $scope.isNewResource = false;
            }
          );
        } else {
          StyleFactory.update(fromSLDEditor, $scope.edit_resource.name);
        }
      } else {
        alert($filter('translate')('model.styles.editor.malformed'));
      }
    };

    StyleFactory.getlist().then(function() {
      $scope.currentResources = StyleFactory.resources.styles;

      FeatureTypeFactory.get().then(function() {
        FeatureTypeFactory.resources.featuretypes.forEach(function(ft) {
          if (angular.isArray(ft.styles) && ft.styles.length > 0) {
            $scope.currentResources.forEach(function(res) {
              if (!Array.isArray(res.features)) {
                res.features = [];
              }
              if (ft.styles.indexOf(res.name) !== -1) {
                res.features.push(ft.name);
                res.isLinked = true;
              }
            });
          }
        });
      });
    });

    $scope.$on('data_modal', function(event, args) {
      if (args.action !== 'edit') {
        return;
      }
      styleDialog = args.dialogObject;

      // New style, just instanciate the editor
      if ($scope.isNewResource) {
        return $timeout(getEditor);
      }

      // Existing style, fetch its SLD
      StyleFactory.get($scope.edit_resource.name).then(function(res) {
        var sld = x2js.xml_str2json(res.data);
        sldUtils.cleanSLD(sld);
        sld = x2js.json2xml_str(sld);
        if (sld) {
          $timeout(function() {
            var editor = getEditor();
            editor.getDoc().setValue(sld.replace(/(>)(<)(\/*)/g, '$1\r\n$2$3'));
            editor.refresh();
            editor.execCommand('selectAll');
            editor.execCommand('indentAuto');
            editor.setCursor(0, 0);
          }, 0);
        }
      });
    });
    $scope.$on('ngDialog.closed', function(event, $dialog) {
      if (styleDialog.id === $dialog.attr('id')) {
        getEditor().toTextArea();
        $scope.codeEditor = null;
      }
    });

    $scope.removeStyle = function() {
      StyleFactory.remove($scope.edit_resource.name);
    };
    $scope.publish = function() {
      // StyleFactory.remove($scope.edit_resource.name);
      StyleFactory.publish($scope.edit_resource.name);
    };
    $scope.publishall = function() {
      StyleFactory.publishall().then(function() {
        toastr.success('Styles publiés');
      });
      //StyleFactory.remove($scope.edit_resource.name);
    };

    $scope.editListCfg = {
      dataModule: 'model',
      resource_type: 'styles',
      cols: ['name', 'isLinked'],
      colsFunction: {
        isLinked: 'booleanToCheck',
      },
      removeTemplate:
        'js/XG/modules/model/views/modals/modal.styles.remove.html',
      removeFunction: $scope.removeStyle,
      extraGlobalActions: [
        {
          label: 'model.featuretypes.style_publish',
          fn: $scope.publishall,
        },
      ],
      extraActions: [
        {
          icon: "<i class='fa fa-google-wallet'></i>",
          label: 'common.featuretypes.publish',
          fn: $scope.publish,
        },
      ],
    };

    $scope.validForm = {};
    $scope.validateName = function() {
      var actualName = $scope.edit_resource.name;

      $scope.$watch(
        'edit_resource.name',
        function(name) {
          $scope.validName = gaJsUtils.checkCustomRegex(name);
          $scope.nameExists = $scope.currentResources.some(function(r) {
            return r.name === name;
          });
          if (
            !$scope.isNewResource &&
            $scope.edit_resource.name === actualName
          ) {
            $scope.nameExists = false;
          }
          $scope.validForm.name = !$scope.nameExists;
        },
        1
      );
    };
  };

  StyleCtrl.$inject = [
    '$scope',
    'FeatureTypeFactory',
    'StyleFactory',
    '$timeout',
    'x2js',
    '$filter',
    'sldUtils',
    'gaJsUtils',
  ];

  return StyleCtrl;
});
