'use strict';
define(function() {
  var gcdatasearch = function(
    FeatureTypeFactory,
    QueryFactory,
    EditFactory,
    $timeout
  ) {
    return {
      templateUrl: 'js/XG/widgets/utilities/data/views/gcdatasearch.html',
      restrict: 'A',
      scope: {
        res: '=res',
        ftid: '=ftid',
        editable: '=',
        searchfields: '=',
      },
      link: function(scope, element, attrs, ctrl) {
        console.log(scope.ftid);
        var fti = FeatureTypeFactory.getFeatureByUid(scope.ftid);
        console.log(fti);

        /**
         * Add a field
         */
        scope.addField = function() {
          var fti = FeatureTypeFactory.getFeatureByUid(scope.ftid);

          scope.cfgfields.fields.push({
            fti: fti,
            operande: '=',
            attributename: false,
            alias: false,
            value: {},
          });
        };

        scope.getAliasFromAttribute = function(attName) {
          var alias = '';
          var fti = FeatureTypeFactory.getFeatureByUid(scope.ftid);
          var atts = fti.attributes;
          for (var i = 0; i < atts.length; i++) {
            if (atts[i].name === attName) {
              alias = atts[i].alias;
            }
          }
          return alias;
        };

        /**
         * Remove a field
         * @param index
         */
        scope.removeField = function(index) {
          scope.cfgfields.fields.splice(index, 1);
        };

        /**
         * When anything is changed, build clause where
         */
        scope.$watch(
          function() {
            return scope.cfgfields;
          },
          function(data) {
            var where = '';
            scope.cfgfields.fields.forEach(function(sf) {
              if (sf.fti && sf.attributename && sf.value[sf.attributename]) {
                if (where != '') {
                  where += ' ' + scope.cfgfields.operande;
                }
                if (sf.operande == '%') {
                  where +=
                    ' ' +
                    sf.attributename +
                    " LIKE '%" +
                    sf.value[sf.attributename] +
                    "%'";
                } else {
                  where +=
                    ' ' +
                    sf.attributename +
                    sf.operande +
                    "'" +
                    sf.value[sf.attributename] +
                    "'";
                }
              }
              if (scope.res && where) scope.res = where;
            });
          },
          1
        );
        scope.res = '1=10';
        scope.reset = function() {
          scope.cfgfields.fields.forEach(function(sf) {
            sf.value = {};
          });
          scope.res = '1=10';
          //var att = scope.cfgfields.fields[0].attributename;
          //scope.cfgfields.fields[0].value[att]=" ";
        };

        scope.operandes = [
          { name: 'equals', value: '=' },
          { name: 'different', value: '<>' },
          { name: 'gt', value: '>' },
          { name: 'gte', value: '>=' },
          { name: 'lt', value: '<' },
          { name: 'lte', value: '<=' },
          { name: 'like', value: '%' },
        ];

        /**
         * Watch on searchField fti && cfgfields.fields.attributename
         * When fti is changed, reset attributename
         * When fti OR attributename is changed, reset the formfield directive
         * (the form-field directive has an ng-if attribute on the condition !resetFields[$index],
         * so we briefly set resetFields[$index] to true to force the redraw of the directive)
         * ONLY IN EDIT VIEW
         */
        scope.$watch(
          'cfgfields',
          function(n, o) {
            if (scope.editable) {
              scope.resetFields = [];
              n.fields.forEach(function(nn, i) {
                if (!angular.isDefined(o.fields[i])) return false;
                // fti or attributename have been changed, gotta reset the formfielddirective
                if (
                  nn.fti.uid != o.fields[i].fti.uid ||
                  nn.attributename != o.fields[i].attributename
                ) {
                  // changed only the fti, delete attributename which is linked to the previous fti
                  if (nn.attributename == o.fields[i].attributename) {
                    delete scope.cfgfields.fields[i].attributename;
                  }
                  scope.resetFields[i] = true;
                  $timeout(function() {
                    scope.resetFields = [];
                  }, 0);
                }
              });
              scope.searchfields = {
                operande: scope.cfgfields.operande,
                fields: [],
              };
              scope.cfgfields.fields.forEach(function(c) {
                if (c.fti != false && c.attributename) {
                  var alias = scope.getAliasFromAttribute(c.attributename);
                  scope.searchfields.fields.push({
                    ftid: c.fti.uid,
                    attributename: c.attributename,
                    operande: c.operande,
                    alias: alias,
                  });
                }
              });
            }
          },
          1
        );

        // init
        // the cfgfields objet is used internally only
        scope.cfgfields = { operande: 'AND', fields: [] };

        // if a config is passed
        if (angular.isDefined(scope.searchfields)) {
          scope.searchfields.fields.forEach(function(sf) {
            scope.cfgfields.fields.push({
              fti: FeatureTypeFactory.getFeatureByUid(sf.ftid),
              ftid: sf.ftid,
              operande: sf.operande,
              attributename: sf.attributename,
              alias: sf.alias,
              value: {},
            });
          });
          scope.cfgfields.operande = scope.searchfields.operande;
        } else {
          if (scope.editable && scope.ftid != undefined) scope.addField();
        }
      },
    };
  };

  gcdatasearch.$inject = [
    'FeatureTypeFactory',
    'QueryFactory',
    'EditFactory',
    '$timeout',
  ];
  return gcdatasearch;
});
