/**
 *
 */
'use strict';
define(function() {
  var ffl2Ctrl = function(
    $scope,
    ngDialog,
    QueryFactory,
    UnitsFactory,
    GlobalServices,
    FeatureTypeFactory,
    $timeout,
    gaJsUtils
  ) {
    var fieldDesc;
    var ind03;
    var fieldType;

    $scope.prepareStoredAsField = function() {
      if ($scope.theField01.valueStoredAs != undefined) {
        //$scope.theField01.objectField = GlobalServices.getStoredValueObj($scope.theField01.valueStoredAs.name);
        GlobalServices.getStoredValueObj(
          $scope.theField01.valueStoredAs.name
        ).then(function(res) {
          $scope.theField01.objectField = res;
          GlobalServices.gotStoredValue($scope.theField01.valueStoredAs.name);
        });
        if ($scope.theField01.fieldDesc == undefined)
          $scope.theField01.fieldDesc = {};
        $scope.theField01.fieldDesc.type = $scope.theField01.valueStoredAs.type;
        if ($scope.theField01.fieldDesc.alias == undefined)
          $scope.theField01.fieldDesc.alias = $scope.theField01.alias;
        if ($scope.theField01.fieldDesc.alias == undefined)
          $scope.theField01.fieldDesc.alias = $scope.theField01.field;
        $scope.theField01.fieldDesc.unit = $scope.theField01.valueStoredAs.unit;
      }

      if ($scope.theField01.storeAs != undefined)
        GlobalServices.storeValueObj(
          $scope.theField01.storeAs,
          $scope.theField01.objectField
        );
    };

    $scope.prepareFieldAsListOfValue = function(fieldDesc) {
      var ind01;

      if (fieldDesc.restrictions == undefined) return;
      //-- Field is restricted to a list of values or yyyyyyy ?
      for (ind01 = 0; ind01 < fieldDesc.restrictions.length; ind01++) {
        if (fieldDesc.restrictions[ind01].type == 'Domain') {
          $scope.theField01.fieldDesc.fieldTypeIsDomain = true;
          $scope.theField01.fieldDesc.listOfValues = [];
          for (var prop in fieldDesc.restrictions[ind01].listofValues) {
            ind03 = $scope.theField01.fieldDesc.listOfValues.length;
            $scope.theField01.fieldDesc.listOfValues[ind03] = {};
            $scope.theField01.fieldDesc.listOfValues[ind03].code = prop;
            $scope.theField01.fieldDesc.listOfValues[ind03].value =
              fieldDesc.restrictions[ind01].listofValues[prop];
          }
        }
      }
    };

    /**
     *     Reset the field name in order it is correctly set when update to database is done.
     *  Now we set it to be the id field name which should look like id_xxx.
     *  This function is called when there is a relation with a selection form.
     *  In this case the property name of the object objectField has been
     *  set with the name of the relation.
     */
    $scope.setIdFieldNameForRelationWithForm = function() {
      if (
        $scope.theField01.relation.componentEnd == $scope.theField01.featureName
      )
        $scope.theField01.objectField.name =
          $scope.theField01.relation.fieldEnd;
      else
        $scope.theField01.objectField.name =
          $scope.theField01.relation.fieldStart;
    };

    $scope.refreshValueList = function(loading) {
      var ind01, feat, mainField, value;
      var defaultValueExists = false;

      if ($scope.theField01.fieldDesc.listOfValues == undefined) return;
      $scope.theField01.fieldDesc.listOfValues.splice(
        0,
        $scope.theField01.fieldDesc.listOfValues.length
      );
      mainField = $scope.getMainFieldForTable();
      if ($scope.theField01.panelUse == 'search')
        $scope.addValueToSelect('', '-- Aucun --');
      for (ind01 = 0; ind01 < $scope.relatedObjects.features.length; ind01++) {
        feat = $scope.relatedObjects.features[ind01];

        if (mainField != null) value = feat.properties[mainField];
        //-- Il y a eut un cas avec marche approbation où une liste vide existe !
        else if (ind01 < $scope.theField01.fieldDesc.listOfValues.length)
          value = $scope.theField01.fieldDesc.listOfValues[ind01].code;
        else value = '';
        $scope.addValueToSelect($scope.getFeatureId(feat), value);

        if (
          $scope.theField01.fieldDesc.listOfValues[ind01].value ==
          $scope.theField01.objectField.value
        )
          defaultValueExists = true;
      }
      //-- objectField may be defined if the field is called
      //-- from a widget with update state.
      if (
        !defaultValueExists &&
        $scope.relatedObjects.features.length != 0 &&
        $scope.theField01.objectField.value == ''
      ) {
        $scope.theField01.objectField.value =
          $scope.theField01.fieldDesc.listOfValues[0].code;
        $scope.dependencyIdForChildren =
          $scope.theField01.fieldDesc.listOfValues[0].code;
        $scope.valueChanged();
      } else {
        $scope.savedValue = $scope.theField01.objectField.value;
        $scope.theField01.objectField.value = '';
        var len = $scope.theField01.fieldDesc.listOfValues.length;
        for (ind01 = 0; ind01 < len; ind01++)
          if (
            $scope.theField01.fieldDesc.listOfValues[ind01].code ==
            $scope.savedValue
          ) {
            if ($scope.theField01.fieldDesc.listOfValues.length != 0) {
              $scope.theField01.objectField.value =
                $scope.theField01.fieldDesc.listOfValues[ind01].code;
              $scope.selectFirstItem();
            }
            break;
          }
        //-- No matching object found so select the first one
        if (ind01 == len && len != 0) {
          $scope.theField01.objectField.value =
            $scope.theField01.fieldDesc.listOfValues[0].code;
          $scope.selectFirstItem();
        }
      }
    };

    $scope.datechanged = function() {
      var abc = 'eee';
    };

    /**
     *       Build list of values for dropdown list in case values come from a table.
     *   If this field depends on another one there is a where clause to build
     *   which restrict the list to those in relation with the main field
     *   (ie the parent of the relation).
     */
    $scope.loadListOfValuesFromTable = function(loading) {
      if ($scope.theField01.relation == undefined) return;
      //-- Get all table records and set the value list used by the select.
      //-- If ID is provided then get related objects
      $scope.theField01.tableDesc = FeatureTypeFactory.getFeatureTypeDesc(
        $scope.theField01.datastoreName,
        $scope.theField01.relation.componentStart
      );
      var where = '';
      if ($scope.parentId != null && $scope.parentId != '')
        where =
          $scope.theField01.fieldDesc.dependsOn.id_enfant +
          '=' +
          $scope.parentId;
      QueryFactory.data($scope.theField01.tableDesc.uid, where).then(function(
        res
      ) {
        //alert(res);
        $scope.relatedObjects = res.data;
        $scope.refreshValueList(loading);
      });
    };

    $scope.prepareStoredAsField();
    if ($scope.theField01 == null)
      $scope.theField01 = $scope.__proto__.theField01;

    fieldDesc = $scope.theField01.fieldDesc;
    if (fieldDesc != undefined && fieldDesc.type != null)
      fieldType = fieldDesc.type.toLowerCase();

    if ($scope.theField01.config != undefined) {
      $scope.theField01.contentType = $scope.theField01.config.contentType;
      if ($scope.theField01.config.type == 'report') {
        $scope.theField01.fieldDesc.fieldTypeIsReport = true;
        //-- When the field is a report the attachment possibility will be managed in the report field
        if (fieldType != undefined)
          $scope.theField01.config.withAttachment =
            fieldType.indexOf('g2c.attachment') != -1;
        $scope.theField01.fieldDesc.fieldTypeIsMultipleAttachments = $scope.theField01.fieldDesc.fieldTypeIsSingleAttachment = $scope.theField01.fieldDesc.fieldTypeIsString = false;
        if (
          $scope.theField01.config.fieldAlias != undefined &&
          $scope.theField01.config.fieldAlias != ''
        )
          $scope.theField01.fieldDesc.alias =
            $scope.theField01.config.fieldAlias;
      }
    } else if (fieldDesc != undefined && fieldDesc.fieldTypeIsRelation) {
      if (fieldDesc.alias == undefined)
        fieldDesc.alias = $scope.theField01.field;
      //-- For M-N relation the input is done using RelationFormField2
      if (
        $scope.theField01.relation.occurence == '1-N' &&
        ($scope.theField01.relation.componentEnd ==
          $scope.theField01.featureName ||
          $scope.theField01.featureName == undefined)
      ) {
        //-- Unless setting specifically says don't display a list of value
        //-- in that case a list of the value read from the table will be displayed.
        if (fieldDesc.selectWithForm === true) {
          fieldDesc.fieldTypeIsRelationWithForm = true;
          $scope.setIdFieldNameForRelationWithForm();
        } else {
          fieldDesc.fieldTypeIsRelationListOfValue = true;
          $scope.loadListOfValuesFromTable(true);
        }
      }
    } else if (fieldDesc != undefined) {
      fieldDesc.fieldTypeIsNumber =
        fieldDesc.type != null &&
        (fieldDesc.type.indexOf('.Integer') != -1 ||
          fieldDesc.type.indexOf('.Long') != -1 ||
          fieldDesc.type.indexOf('.Double') != -1 ||
          fieldDesc.type.indexOf('.Float') != -1);

      fieldDesc.fieldTypeIsMultipleAttachments =
        fieldType.indexOf('g2c.attachments') != -1;
      if (!fieldDesc.fieldTypeIsMultipleAttachments)
        fieldDesc.fieldTypeIsSingleAttachment =
          fieldType.indexOf('g2c.attachment') != -1;
      fieldDesc.fieldTypeIsBoolean = fieldType.indexOf('.boolean') != -1;
      fieldDesc.fieldTypeIsDate = fieldType.indexOf('.date') != -1;
      if (fieldDesc.fieldTypeIsDate)
        $scope.$watch('theField01.objectField.value', $scope.datechanged);
      if (
        fieldDesc.name != undefined &&
        fieldDesc.name.substr(0, 13) == 'g2cenvoimail_'
      ) {
        fieldDesc.fieldTypeIsSendMail = true;
      } else {
        fieldDesc.fieldTypeIsString = fieldType.indexOf('.string') != -1;
        if (
          fieldDesc.fieldTypeIsString &&
          (fieldDesc.size == 0 || fieldDesc.size > 500)
        ) {
          $scope.theField01.fieldDesc.fieldTypeIsString = false;
          $scope.theField01.fieldDesc.fieldTypeIsComment = true;
        } else $scope.maxLength = fieldDesc.size;
      }

      if (fieldDesc.fieldTypeIsBoolean) {
        //-- Do we have to set a default value to the chackbox
        if (
          $scope.theField01.objectField == null ||
          $scope.theField01.objectField.value == null ||
          $scope.theField01.objectField.value == ''
        ) {
          //-- Check box default value is TRUE
          if ($scope.theField01.objectField == undefined)
            $scope.theField01.objectField = {};
          $scope.theField01.objectField.name = fieldDesc.name;
          $scope.theField01.objectField.value = '1';
        }
      }
      $scope.prepareFieldAsListOfValue(fieldDesc);
    }

    /*
Inutile mais gardé pour le cas où.
		$scope.getStepindex = function ()
		{
			var iStep;
			for (iStep=0;iStep<$scope.steps.length;iStep++)
			    {
			     if ($scope.steps[iStep].featureName==$scope.$parent.$parent.theField01.relation.componentEnd)
			         return iStep;
			    }
		}
*/

    $scope.fieldValueChanged4Steps = function() {
      $scope.theStepIndex = $scope.getStepindex();
      $scope.stepReadOnly =
        $scope.steps[$scope.theStepIndex - 1] != undefined &&
        $scope.steps[$scope.theStepIndex - 1].mandatory == 1 &&
        $scope.steps[$scope.theStepIndex - 1].allValuesAreNull === true;
    };

    $scope.prepareFieldDesc = function() {
      //-- ALIAS --
      //-- In case of a more input field, no description is provided
      //-- and we don't want to display any alias.
      if (fieldDesc == undefined) {
        fieldDesc = {};
        fieldDesc.alias = '';
      }
      //-- No alias on the field description nor in the configuration so use database field name.
      if (fieldDesc.alias == null) fieldDesc.alias = fieldDesc.name;
      //                 $scope.theField01.fieldDesc.alias = fieldDesc.name;

      //-- READONLY --
      if ($scope.theStep == undefined || $scope.theStep.index == 0) {
        //$scope.theStepIndex = $scope.theStep.index;
        $scope.stepReadOnly = false;
      } else {
        //$scope.theStepIndex = $scope.getStepindex();
        $scope.theStepIndex = $scope.theStep.index;
        $scope.previousStep = $scope.steps[$scope.theStepIndex - 1];
        $scope.$watch(
          'previousStep.allValuesAreNull',
          $scope.fieldValueChanged4Steps
        );
      }
      //-- readOnly default value is false
      if (fieldDesc.readOnly === undefined) fieldDesc.readOnly = false;
      //                 $scope.theField01.fieldDesc.readOnly = false;
      if ($scope.theField01.disabledFromParent) {
        fieldDesc.readOnly = true;
        $scope.theField01.mode = 'readonly';
      } else if ($scope.theField01.mode == 'readonlyWhenNotNull') {
        if ($scope.theField01.objectField.value != null) {
          fieldDesc.readOnly = true;
          $scope.theField01.mode = 'readonly';
        } else {
          fieldDesc.readOnly = false;
          $scope.theField01.mode = 'write';
        }
      }
      $scope.initialReadOnly = fieldDesc.readOnly;

      if ($scope.theField01.fieldDesc != undefined) {
        var dep = $scope.theField01.fieldDesc.visibilityDependsOn;
        if (dep == undefined || dep.defaultVisibility == undefined)
          $scope.visible = true;
        else $scope.visible = dep.defaultVisibility == 'true';
      }
    };

    /**
     *       Extract id value from id string which looks like
     *    "featuretypename.X" where X is the identifier value.
     */
    $scope.getFeatureId = function(feature) {
      var indPt;

      indPt = feature.id.indexOf('.');
      if (indPt == -1) return feature.id;
      else return feature.id.substr(indPt + 1);
    };

    /**
     *       Extract id value from id string which looks like
     *    "featuretypename.X" where X is the identifier value.
     */
    $scope.getLayerName = function(feature) {
      var indPt;

      indPt = feature.id.indexOf('.');
      if (indPt == -1) return feature.id;
      else return feature.id.substr(0, indPt);
    };

    /**
     *      Called by timer to check if a character has been input
     *   in less than 1 second. In that case we consider the input is not finished.
     *   In the other case, we run the necessary treatment for new value input.
     */
    $scope.checkInputIsDone = function() {
      var d = new Date();
      var t = d.getTime();

      if ($scope.inputLastTime != undefined)
        if (t - $scope.inputLastTime < 1000)
          setTimeout($scope.checkInputIsDone, 1000);
        else {
          $scope.inputLastTime = undefined;
          $scope.valueChangedTreatment();
        }
    };

    $scope.checkInput = function() {
      var d = new Date();
      var t = d.getTime();

      if (
        (($scope.theField01.fieldDesc.fieldTypeIsNumber ||
          $scope.theField01.fieldDesc.fieldTypeIsString) &&
          !$scope.theField01.fieldDesc.fieldTypeIsDomain) ||
        $scope.theField01.fieldDesc.fieldTypeIsComment
      ) {
        if ($scope.inputLastTime == undefined) {
          $scope.inputLastTime = t;
          setTimeout($scope.checkInputIsDone, 1000);
        } else $scope.inputLastTime = t;
        return false;
      } else return true;
    };

    $scope.checkModelvalue = function() {
      var val;
      val = $scope.theField01.objectField.value;
      $scope.theField01.objectField.value = val;
    };

    $scope.executeFieldActions = function() {
      //-- If actions are configure on the field send them to the main parent
      //-- (widget typeprojet) in order to execute them.
      if ($scope.theField01.fieldDesc.fieldActions != undefined) {
        var actions = $scope.theField01.fieldDesc.fieldActions;
        for (var indAction = 0; indAction < actions.length; indAction++) {
          if (
            actions[indAction].when == undefined ||
            actions[indAction].when == 'change' ||
            $scope.theField01.objectField.value == actions[indAction].when
          )
            $scope.$emit('thereIsAnActionToTriggerAfterChange', {
              actions: actions[indAction].actions,
              newValue: $scope.theField01.objectField.value,
              parentId: $scope.objectId,
            });
        }
      }
    };

    /**
     *      Management of fields depending on this one according to
     *   a change of value. This dependency is a relational one
     *   not a logical one.
     */
    $scope.emitToDependents = function(dep) {
      for (var ind = 0; ind < dep.length; ind++) {
        if (dep[ind].dependent != null) {
          var data = {};
          data.childTableName = dep[ind].dependent;
          if ($scope.dependencyIdForChildren != null)
            data.parentId = $scope.dependencyIdForChildren;
          else data.parentId = $scope.theField01.objectField.value;
          $scope.$emit('dependencyParentChangedTriggered', data);
          $scope.dependencyIdForChildren = null;
        }
      }
    };

    /**
     *      Management of fields depending on this one according to
     *   a change of value. This dependency is a logical one
     *   not a relational one.
     */
    $scope.manageDependentFields = function() {
      var data, ind, dep;

      if ($scope.theField01.fieldDesc != undefined)
        dep = $scope.theField01.fieldDesc.dependentFields;
      if (dep == undefined && $scope.theField01.fieldDesc != undefined)
        dep = $scope.theField01.fieldDesc.dependencies;
      if (dep != undefined) {
        for (ind = 0; ind < dep.length; ind++) {
          data = {};
          data.target = dep[ind];
          data.source = $scope.theField01.fieldDesc.name;
          data.value = $scope.theField01.objectField.value;
          if (
            (data.value == '' || data.value == null) &&
            $scope.manageDepFieldInit
          ) {
            if ($scope.manageDepFieldInitCnt++ < 5)
              $timeout($scope.manageDependentFields, 750);
            else $scope.manageDepFieldInit = false;
          } else {
            $scope.manageDepFieldInit = false;
            $scope.$emit('logicalDependencyParentChangedTriggered', data);
          }
        }
      }
    };

    /**
     *       Method called after modification of field content.
     */
    $scope.valueChangedTreatment = function(param) {
      if (
        $scope.steps != undefined &&
        $scope.controlFields != undefined &&
        !$scope.controlFields({
          theField01: $scope.theField01,
          theStep: $scope.steps[$scope.theStepIndex],
        })
      )
        gaJsUtils.errorMessage('Valeur de champ incorrecte !');

      if ($scope.fieldHasUnit)
        //-- Only to update the value that will be stored
        $scope.unitChanged();

      $scope.executeFieldActions();

      if ($scope.$parent.valueChangedFunction === true) {
        $scope.$parent.valueChanged(param);
      }

      var dep = $scope.theField01.fieldDesc.dependencies;
      if (dep != null) $scope.emitToDependents(dep);

      $scope.manageDependentFields();
    };

    /**
     *       Method called after modification of field content.
     */
    $scope.valueChanged = function(param) {
      if ($scope.checkInput()) $scope.valueChangedTreatment(param);
    };

    $scope.open = function($event) {
      $event.preventDefault();
      $event.stopPropagation();

      $scope.opened = true;
    };

    $scope.getMainFieldsForTable = function() {
      if ($scope.theField01.relatedObjectFields != undefined)
        return $scope.theField01.relatedObjectFields;
      else alert('Pas de champs configurés pour afficher dans la liste !');
      return null;
    };

    $scope.tableSelectSelectionDone = function(object) {
      //-- Single selection so the selected object is received as a parameter
      $scope.theField01.objectField.value = QueryFactory.getFeatureId(object);

      var fields = $scope.getMainFieldsForTable();
      $scope.theField01.objectField.valueToDisplay = '';
      if (fields == null || fields.length == 0)
        $scope.theField01.objectField.valueToDisplay += QueryFactory.getFeatureId(
          object
        );
      else
        for (var ind = 0; ind < fields.length; ind++)
          if (fields[ind] == 'id')
            $scope.theField01.objectField.valueToDisplay +=
              QueryFactory.getFeatureId(object) + ' ';
          else
            $scope.theField01.objectField.valueToDisplay +=
              object.properties[fields[ind].field] + ' ';

      //-- Give to the parents the information that a value has been modified.
      $scope.valueChanged();
    };

    $scope.openForm = function() {
      var template;
      var childScope = $scope.$new(true, $scope);
      childScope.ConfigName = $scope.theField01.configName;
      childScope.tableSelectSelectionDone = $scope.tableSelectSelectionDone;
      childScope.selectionType = 'single';
      childScope.meAsNgDialog = ngDialog;
      template =
        "<div TableSelectAndUpdateDirective style='width:100%;overflow-x:scroll;'></div>";
      ngDialog.open({
        template: template,
        plain: true,
        scope: childScope,
        className: 'ngdialog-theme-plain width800',
      });
    };

    $scope.unitChanged = function() {
      if ($scope.currentUnitFactor.value != undefined) {
        $scope.theField01.objectField.value =
          $scope.numericValue.value * $scope.currentUnitFactor.value.factor;
        $scope.unitHasChangedForObjectvalueChanged = true;
      }
    };
    $scope.objectValueChanged = function(newValue, oldValue) {
      if ($scope.fieldHasUnit && !$scope.unitHasChangedForObjectvalueChanged)
        $scope.numericValue.value = $scope.theField01.objectField.value;
      $scope.unitHasChangedForObjectvalueChanged = false;
    };

    $scope.initUnit = function() {
      var unitName, unitDesc;
      var fd = $scope.theField01.fieldDesc;
      var abc = '';
      //-- Cas où on met "_field" dans la propriété JSON (par exemple afin de ne pas s'occuper du champ).')
      if ($scope.theField01.field == undefined && fd == undefined) return;
      if (
        fd == undefined &&
        $scope.theField01.field != undefined &&
        $scope.theField01.field.substr(0, 13) != '__moreInputs_'
      )
        gaJsUtils.errorMessage('fd is undefined');
      if (fd == undefined || fd.unit == undefined || fd.unit.type == undefined)
        $scope.fieldHasUnit = false;
      else {
        $scope.fieldHasUnit = true;
        unitName = fd.unit.type;
        $scope.currentUnitFactor = {};
        $scope.numericValue = {};
        //-- Initial value (in case there is one)
        //-- Can be undefined in case of a stored value (managed thru GlobalServices).
        if ($scope.theField01.objectField != undefined)
          $scope.numericValue.value = $scope.theField01.objectField.value;
        UnitsFactory.getUnitDescription(unitName).then(function(res) {
          $scope.unitDesc = res;
          if ($scope.unitDesc.multiple.length != 0) {
            $scope.$watch('currentUnitFactor.value', $scope.unitChanged);
            //-- Next watch is useful once because theField01.objectField.value
            //-- changes out of tis directive only when the query from parent (relation form field)
            //-- get the value after this directive be created.
            $scope.$watch(
              'theField01.objectField.value',
              $scope.objectValueChanged
            );
            for (var ind = 0; ind < $scope.unitDesc.multiple.length; ind++)
              if (
                $scope.unitDesc.multiple[ind].factor == fd.unit.defaultFactor
              ) {
                $scope.dbUnit = $scope.unitDesc.multiple[ind].symbol;
                $scope.currentUnitFactor.value = $scope.unitDesc.multiple[ind];
                break;
              }
          }
        });
      }
    };

    $scope.emptyField = function() {
      if ($scope.theField01.objectField.name == '__geom__')
        $scope.theField01.objectField.value.coordinates = null;
      else {
        if ($scope.theField01.fieldDesc.fieldTypeIsNumber) {
          $scope.theField01.objectField.value = undefined;
          if ($scope.numericValue != undefined)
            $scope.numericValue.value = undefined;
        } else $scope.theField01.objectField.value = '';
        if ($scope.theField01.objectField.valueToDisplay !== undefined)
          $scope.theField01.objectField.valueToDisplay = '';
        if ($scope.theField01.fieldDesc.fieldTypeIsRelation)
          $scope.theField01.objectId = null;
      }
    };

    $scope.openCommentInput = function() {
      var template;
      var childScope = $scope.$new(false, $scope);
      if ($scope.theField01.mode == 'readonly')
        template =
          "<textarea ng-model='theField01.objectField.value' readonly ng-change='valueChanged()' style='width:500px;height:450px;'><textarea>";
      else
        template =
          "<textarea ng-model='theField01.objectField.value' ng-change='valueChanged()' style='width:500px;height:450px;'><textarea>";
      ngDialog.open({ template: template, plain: true, scope: childScope });
    };

    $scope.$on('setFieldMode', function(event, data) {
      if (data.setFieldMode.fieldType == 'ffl2') {
        if (data.setFieldMode.mode == 'readonly') {
          if (
            !$scope.theField01.fieldDesc.fieldTypeIsRelation ||
            $scope.theField01.fieldDesc.fieldTypeIsRelationWithForm
          )
            $scope.theField01.fieldDesc.readOnly = true;
        } else if (data.setFieldMode.mode == 'initial')
          $scope.theField01.fieldDesc.readOnly = $scope.initialReadOnly;
        //-- mode == 'write'
        else $scope.theField01.fieldDesc.readOnly = false;

        if ($scope.theField01.fieldDesc.readOnly)
          $scope.theField01.mode = 'readonly';
        else $scope.theField01.mode = 'write';
      }
    });

    $scope.$on('gotObjectId', function(event, data) {
      if (data.objectId == null) $scope.emptyField();
    });

    /**
     *     We are notified that an object with dependent field have been modified by the user.
     *  So we check that this field is dependent of the modified field.
     *  If so then change the input field description according to the new value.
     *  This allows to disable a field depending on the value of another one
     */
    $scope.$on('logicalDependencyParentChangedDispatched', function(
      event,
      data
    ) {
      var dep;
      if (
        $scope.theField01.fieldDesc != undefined &&
        data.target == $scope.theField01.fieldDesc.name
      ) {
        dep = $scope.theField01.fieldDesc.enabledDependsOn;
        if (dep != undefined && dep.field == data.source)
          if (dep.equals == '!NULL!')
            $scope.enabled = data.value == null || data.value == '';
          else $scope.enabled = data.value == dep.equals;

        dep = $scope.theField01.fieldDesc.visibilityDependsOn;
        if (dep != undefined && dep.field == data.source)
          if (dep.equals == '!NULL!')
            $scope.visible = data.value == null || data.value == '';
          else {
            if (dep.equals != undefined)
              $scope.visible = data.value == dep.equals;
            else if (dep.in != undefined)
              $scope.visible = dep.in.indexOf("'" + data.value + "'") != -1;
          }
      }
    });

    $scope.prepareFieldDesc();

    $scope.unitList = [];
    $scope.initUnit();

    $scope.manageDepFieldInitCnt = 0;
    $scope.manageDepFieldInit = true;
    $timeout($scope.manageDependentFields, 750);
  };

  ffl2Ctrl.$inject = [
    '$scope',
    'ngDialog',
    'QueryFactory',
    'UnitsFactory',
    'GlobalServices',
    'FeatureTypeFactory',
    '$timeout',
    'gaJsUtils',
  ];
  return ffl2Ctrl;
});
