'use strict';
define(function() {
  var bacAvisControle = function(BacAppFactory, ancBacTools) {
    return {
      templateUrl:
        'js/XG/widgets/bacapp/main/views/directives/bac_avis_controle.html',
      restrict: 'EA',
      scope: {
        typeControle: '=',
        cdata: '=',
        ctrlClos: '=',
        labelKey: '=?',
        controleCommentConfig: '=?',
        agent: '=?', // used to render agent on user picker
      },
      link: function(scope, elt, attrs, ctrl) {
        scope.showConfig = angular.isDefined(scope.controleCommentConfig)
          ? true
          : false;

        scope.avisCtrl = BacAppFactory.appCfg.main.dossierCfg.avisControles;

        // pick agent et resp
        scope.$watch(
          'agentPicker.value',
          function(a) {
            if (a && angular.isDefined(a)) {
              if (!angular.isDefined(scope.cdata.conformite)) {
                scope.cdata.conformite = {};
              }
              scope.cdata.conformite.agent = a.vorname + ' ' + a.name;
            }
          },
          1
        );
        scope.$watch(
          'respPicker.value',
          function(r) {
            if (r && angular.isDefined(r)) {
              if (!angular.isDefined(scope.cdata.conformite)) {
                scope.cdata.conformite = {};
              }
              scope.cdata.conformite.responsable = r.vorname + ' ' + r.name;
            }
          },
          1
        );

        scope.resetAvis = function(type) {
          if (type == 'agent') delete scope.cdata.conformite.valeur_agent;
          if (type == 'responsable') delete scope.cdata.conformite.valeur;
        };

        scope.checkAvisActif = function(label, typeCtrl, fonction) {
          console.log(typeCtrl);
          for (var i = 0; i < scope.avisCtrl.length; i++) {
            if (
              scope.avisCtrl[i].label === label &&
              scope.avisCtrl[i].type_controle === typeCtrl
            ) {
              if (
                angular.isDefined(scope.avisCtrl[i].actif) &&
                scope.avisCtrl[i].actif === false
              ) {
                if (fonction === 'responsable')
                  scope.avisInactifResponsable = true;
                scope.valeur_inactive = scope.cdata.conformite.valeur;
                if (fonction === 'agent') scope.avisInactifAgent = true;
                scope.valeur_inactive_agent =
                  scope.cdata.conformite.valeur_agent;
              }
            }
          }
        };

        scope.copyAvisAgent = function() {
          ancBacTools.copyAvisAgent(scope.cdata);
        };
      },
    };
  };

  bacAvisControle.$inject = ['BacAppFactory', 'ancBacTools'];
  return bacAvisControle;
});
