'use strict';
define(function() {
  /**
   * controleFormCfg
   * Retrieve the configuration (obligatoire/discriminant) for the current type of form
   * @param AncAppFactory
   */
  var controleFormCfg = function(
    AncAppFactory,
    ConfigFactory,
    gaJsUtils,
    $timeout,
    BacAppFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/ancapp/main/views/directives/controle_form_cfg.html',
      restrict: 'EA',
      scope: {
        type: '=',
        formData: '=',
        validation: '=',
        apptype: '=?',
      },
      link: function(scope, elt, attrs, ctrl) {
        var obligatoireFields = [];
        var discriminantFields = [];

        var CurrentAppFactory =
          scope.apptype == 'bac' ? BacAppFactory : AncAppFactory;

        scope.validation = {
          obligatoire: 0,
          filled_obligatoire: 0,
          discriminant: 0,
          filled_discriminant: 0,
        };

        /**
         * goToField
         * @param key
         * @param type
         */
        scope.goToField = function(key, type) {
          var element = angular.element('[ng-model="' + key + '"]');

          if (!element[0]) {
            element = angular.element('[data-ng-model="' + key + '"]');
            if (!element[0]) {
              element = angular.element('[data-for="' + key + '"]');
            }
          }

          // multitabbed form (ex : fiche D)
          if (angular.element('.mainCtrlFormTabs').length) {
            angular.forEach(angular.element('.mainCtrlFormTab'), function(
              value,
              key
            ) {
              var a = angular.element(value);

              // expand that tab first
              if (a.find(element).length) {
                //TODO RB unjquery if necessary
                $timeout(function() {
                  $('.mainCtrlFormTabs > ul > li')
                    .eq(key)
                    .find('a')
                    .trigger('click');
                });
              }
            });
          }

          $timeout(function() {
            var ctrlForm = angular.element('.ctrlForm');
            // open all collapses
            angular.forEach(angular.element('.panel-collapse'), function(
              value,
              key
            ) {
              angular.element(value).addClass('in in_forced');
            });
            // scrollto
            $timeout(function() {
              gaJsUtils.scrollToElement(ctrlForm[0], element[0], 500);
            });
          });
        };

        if (typeof AppAndroid !== 'undefined') {
          CurrentAppFactory.getAllCtrlFormCfg().then(function(res) {
            // AncAppFactory.getCtrlFormCfg(scope.type).then(function(res){
            console.log(res.data);
            if (res.data == '') return;
            var formCfg = res.data;
            var type = scope.type;
            var formCfg = formCfg[type];
            if (formCfg == undefined) return;
            if (
              angular.isDefined(formCfg.obligatoire) &&
              angular.isDefined(formCfg.discriminant)
            ) {
              var hasObligatoireCfg =
                formCfg.obligatoire && Object.keys(formCfg.obligatoire).length;
              var hasDiscriminantCfg =
                formCfg.discriminant &&
                Object.keys(formCfg.discriminant).length;

              scope.showDirective = hasObligatoireCfg || hasDiscriminantCfg;

              $timeout(function() {
                ['obligatoire', 'discriminant'].forEach(function(type) {
                  if (angular.isDefined(formCfg[type])) {
                    for (var j in formCfg[type]) {
                      if (formCfg[type][j].value) {
                        var key = j;
                        var subkey = false;

                        if (type == 'discriminant') {
                          var k = j.split('.');
                          subkey = k.pop();
                          key = k.join('.');
                        }

                        var label = angular.element('[data-for="' + key + '"]');

                        if (type == 'obligatoire') {
                          var element = angular.element(
                            '[ng-model="' + key + '"]'
                          );

                          element.prop('required', true);
                          label.addClass('ctrlFormRequired');
                          obligatoireFields.push(key);

                          // commentaire
                          if (formCfg[type][j].text) {
                            var icone = angular.element(
                              '<div class="formCfgComment">' +
                                '<i class="fa fa-comment-o"></i>' +
                                '<div class="ttip">' +
                                formCfg[type][j].text +
                                '</div>' +
                                '</div>'
                            );
                            icone.insertAfter(label);
                          }
                        }
                        if (type == 'discriminant') {
                          // foreach choice
                          var choiceIndex = -1;
                          angular.forEach(
                            angular.element('[ng-model="' + key + '"]'),
                            function(elem, index) {
                              var valz = angular.element(elem).val();
                              if (valz == subkey) {
                                choiceIndex = index;
                              }
                            }
                          );

                          if (choiceIndex !== -1) {
                            var sublabel = angular.element(
                              '[data-forvalue="' + key + '"]'
                            )[choiceIndex];

                            discriminantFields.push(key + '.' + subkey);
                            var ngsublabel = angular.element(sublabel);
                            ngsublabel.addClass('discriLabel');

                            // commentaire
                            if (formCfg[type][j].text) {
                              var icone = angular.element(
                                '<div class="formCfgComment discriComment">' +
                                  '<i class="fa fa-comment-o"></i>' +
                                  '<div class="ttip">' +
                                  formCfg[type][j].text +
                                  '</div>' +
                                  '</div>'
                              );
                              icone.insertAfter(sublabel);
                            }
                          }
                        }

                        formCfg[type][j].key = key;
                        formCfg[type][j].label = label.text();
                        scope.validation[type]++;
                      }
                    }
                  }
                });
                scope.formCfg = formCfg;
              });
            }
          });
        } else {
          CurrentAppFactory.getCtrlFormCfg(scope.type).then(function(res) {
            // AncAppFactory.getCtrlFormCfg(scope.type).then(function(res){
            console.log(res.data);
            if (res.data == '') return;
            var formCfg = res.data;
            if (formCfg == undefined) return;
            if (
              angular.isDefined(formCfg.obligatoire) &&
              angular.isDefined(formCfg.discriminant)
            ) {
              var hasObligatoireCfg =
                formCfg.obligatoire && Object.keys(formCfg.obligatoire).length;
              var hasDiscriminantCfg =
                formCfg.discriminant &&
                Object.keys(formCfg.discriminant).length;

              scope.showDirective = hasObligatoireCfg || hasDiscriminantCfg;

              $timeout(function() {
                ['obligatoire', 'discriminant'].forEach(function(type) {
                  if (angular.isDefined(formCfg[type])) {
                    for (var j in formCfg[type]) {
                      if (formCfg[type][j].value) {
                        var key = j;
                        var subkey = false;

                        if (type == 'discriminant') {
                          var k = j.split('.');
                          subkey = k.pop();
                          key = k.join('.');
                        }

                        var label = angular.element('[data-for="' + key + '"]');

                        if (type == 'obligatoire') {
                          var element = angular.element(
                            '[ng-model="' + key + '"]'
                          );

                          element.prop('required', true);
                          label.addClass('ctrlFormRequired');
                          obligatoireFields.push(key);

                          // commentaire
                          if (formCfg[type][j].text) {
                            var icone = angular.element(
                              '<div class="formCfgComment">' +
                                '<i class="fa fa-comment-o"></i>' +
                                '<div class="ttip">' +
                                formCfg[type][j].text +
                                '</div>' +
                                '</div>'
                            );
                            icone.insertAfter(label);
                          }
                        }
                        if (type == 'discriminant') {
                          // foreach choice
                          var choiceIndex = -1;
                          angular.forEach(
                            angular.element('[ng-model="' + key + '"]'),
                            function(elem, index) {
                              var valz = angular.element(elem).val();
                              if (valz == subkey) {
                                choiceIndex = index;
                              }
                            }
                          );

                          if (choiceIndex !== -1) {
                            var sublabel = angular.element(
                              '[data-forvalue="' + key + '"]'
                            )[choiceIndex];

                            discriminantFields.push(key + '.' + subkey);
                            var ngsublabel = angular.element(sublabel);
                            ngsublabel.addClass('discriLabel');

                            // commentaire
                            if (formCfg[type][j].text) {
                              var icone = angular.element(
                                '<div class="formCfgComment discriComment">' +
                                  '<i class="fa fa-comment-o"></i>' +
                                  '<div class="ttip">' +
                                  formCfg[type][j].text +
                                  '</div>' +
                                  '</div>'
                              );
                              icone.insertAfter(sublabel);
                            }
                          }
                        }

                        formCfg[type][j].key = key;
                        formCfg[type][j].label = label.text();
                        scope.validation[type]++;
                      }
                    }
                  }
                });
                scope.formCfg = formCfg;
                $timeout(function() {
                  checkFormData();
                });
              });
            }
          });
        }

        var checkFormData = function() {
          if (scope.formData.datesDossier.date_controle) {
            // à la toute première mis à jour de la date, l'heure est à minuit de base, donc on la passe à 8h00
            if (new Date(scope.formData.datesDossier.date_controle).getHours() === 0) {
              scope.formData.datesDossier.date_controle = new Date(scope.formData.datesDossier.date_controle).setHours(8,0);
            }
          }
          if (!scope.formCfg) return;

          var nbFilledObligatoire = 0;
          var nbFilledDiscriminant = 0;

          obligatoireFields.forEach(function(key) {
            var objValid = false;
            var obj = gaJsUtils.checkNestedProperty(
              key.replace('cdata.', ''),
              scope.formData
            );

            if (
              obj !== false &&
              obj != null &&
              obj !== '' &&
              !angular.equals(obj, {})
            ) {
              objValid = true;
              nbFilledObligatoire++;
            }
            scope.formCfg.obligatoire[key].valid = objValid;
          });

          discriminantFields.forEach(function(key) {
            var objValid = true;

            var subkey, pre;
            pre = key.split('.');
            subkey = pre.pop();
            pre = pre.join('.');

            var obj = gaJsUtils.checkNestedProperty(
              pre.replace('cdata.', ''),
              scope.formData
            );

            if (obj == subkey) {
              objValid = false;
              nbFilledDiscriminant++;
            }
            scope.formCfg.discriminant[key].valid = objValid;
          });
          scope.validation.filled_obligatoire = nbFilledObligatoire;
          scope.validation.filled_discriminant = nbFilledDiscriminant;
        };

        var watchFormData = scope.$watch(
          'formData',
          function(formData) {
            checkFormData();
          },
          1
        );

        // cleanup
        scope.$on('$destroy', function() {
          watchFormData();
        });
      },
    };
  };

  controleFormCfg.$inject = [
    'AncAppFactory',
    'ConfigFactory',
    'gaJsUtils',
    '$timeout',
    'BacAppFactory',
  ];
  return controleFormCfg;
});
