'use strict';
define(function () {
  var constructionAutomatiqueHpo = function (
    HpoChantiersServices,
    HpoCarteAppFactory,
    QueryFactory,
    AlertHpoFactory,
    gaDomUtils,
    $filter,
    $rootScope,
    $timeout,
    ngDialog,
    FeatureTypeFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/chantiersautomatique/views/directives/construction_chantiers_automatique.html',
      restrict: 'EA',
      scope: {
      },
      link: function (scope, elt, attrs, ctrl) {
        const config = HpoCarteAppFactory.getInitProvider().getHpoConfig();
        scope.ftiprevision = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'prevision'
        )[0];
        scope.ftihistory = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'modal_historic'
        )[0];
        scope.ftijeudonnee = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'jeu_de_donnee'
        )[0];
        scope.fticalage = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'calage'
        )[0];
        scope.ftiChantierAutomatique = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'hpo_chantier_automatique'
        )[0];
        
        scope.chantierAutomatiqueAttribute = scope.ftiChantierAutomatique.attributes.filter((x) => {
            if(!['CRITERIA','CONSTRAINTS','OPTIMIZATION_CRITERIA','PREVISION_TABLE_CASSANDRA','INFO','SENSITIVE_CONNECTIONS'].includes(x.name)){
              return x;
            }
        })
        scope.ftiChantiers = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'chantiers'
        )[0];
        var getExistingNames = function() {
          gaDomUtils.showGlobalLoader();
          var where = '';
          if (scope.currentModel && scope.currentModel.namechantierautomatique)
            where += ' NOT ("NAME_CHANTIER_AUTOMATIQUE" = \'' + scope.currentModel.namechantierautomatique + "')";
          QueryFactory.dataattributeCorrectedDate(
            scope.ftiChantierAutomatique.uid,
            'NAME_CHANTIER_AUTOMATIQUE',
            where
          ).then(
            function(res) {
              gaDomUtils.hideGlobalLoader();
              if (res && res.data) {
                scope.existingNames = res.data;
              } else {
                AlertHpoFactory.showErrorMessage(res);
              }
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };
        getExistingNames();
        scope.datatableHeightHistoric =
          angular.element('.xgos_content').height() -
          angular.element('#xgos_nav').height() -
          110 +
          'px';
        scope.currentModel = {};
        scope.currentModel.ftiChantierAutomatique = scope.ftiChantierAutomatique.uid;
        scope.currentModel.optimizationcriteria = {
          forecastbreakagerate: true,
          lengthofconstruction: true,
          proportionoftrack: true,
          hazardwaterloss: true,
          hazardtrafic: true,
          priorconnectionindicator: true,
          sensitiveConnections: true
        }

        scope.currentModel.sensitiveConnections = {
          attribute: undefined,
          values: []
        }

        scope.previsionChanged = () => {
          scope.connectionsFti = undefined;
          scope.canaFti = undefined;
          scope.currentModel.sensitiveConnections.attribute = undefined;
          scope.currentModel.sensitiveConnections.values = [];
          if(scope.currentModel.info && scope.currentModel.info.IDENTIFIANT_MODELE){
            QueryFactory.data(
              scope.ftihistory.uid,
              `"IDENTIFIANT" = '${scope.currentModel.info.IDENTIFIANT_MODELE}'` || '1=1'
            ).then(res =>{
              if(res && res.data && Array.isArray(res.data.features) && res.data.features.length>0){
                const idJeuDonnee = res.data.features[0].properties.ID_JEU_DONNEE
                QueryFactory.data(
                  scope.ftijeudonnee.uid,
                  `"IDENTIFIANT" = '${idJeuDonnee}'` || '1=1'
                ).then(resJdd =>{
                  if(resJdd && resJdd.data && Array.isArray(resJdd.data.features) && resJdd.data.features.length>0){
                    const jddProperties = resJdd.data.features[0].properties;
                    scope.currentConfig = config.currentResources.find(resource => resource.uid === jddProperties.UID_TABLE_DONNEE &&  resource.defail_uid === jddProperties.UID_TABLE_FUITE);
                    if(scope.currentConfig.connections){
                      scope.connectionsFti = FeatureTypeFactory.getFeatureByUid(scope.currentConfig.connections);
                    }
                    if(scope.currentConfig.uid){
                      scope.canaFti = FeatureTypeFactory.getFeatureByUid(scope.currentConfig.uid);
                    }
                  }
                });
              }
            });
          }
        }

        scope.sensitiveConnectionsAttributeChanged = () => {
          if(scope.currentConfig && scope.currentConfig.connections && scope.currentModel.sensitiveConnections.attribute){
            scope.connectionsValues = [];
            QueryFactory.dataattribute(
              scope.currentConfig.connections, scope.currentModel.sensitiveConnections.attribute).then(res => {
                if(res && res.data){
                  scope.connectionsValues = res.data;
                }
              })
          }
        }


        scope.statuses = [ 'Draft', 'Pending', 'Live', 'Archived', 'Deleted' ];
        scope.currentModel.constraints = {};
        scope.currentModel.criteria = {};

        scope.tabs = [
          {
            title: 'hpo.chantiersautomatique.tabs.criteriaconstraintesenrichment',
          },
          {
            title: 'hpo.chantiersautomatique.tabs.chantiersautomatiqueList',
          }
        ];
        scope.getExistingprevision = function () {
          gaDomUtils.showGlobalLoader();
          QueryFactory.data(
            scope.ftiprevision.uid,
            scope.where || '1=1',
            HpoCarteAppFactory.getAppFactory().getSrid(),
            '',
            '',
            ''
          ).then(
            function (res) {
              gaDomUtils.hideGlobalLoader();
              if (res.data && res.data.features) {
                scope.existingModels = res.data.features;
              } else {
                AlertHpoFactory.showErrorMessage(res);
              }
            },
            function (res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };

        scope.translateFtiAttributes = HpoCarteAppFactory.getAppFactory().getTranslateAttributes(
          scope.ftiChantierAutomatique.name
        );
        scope.hideFilter = Object.keys(scope.translateFtiAttributes);

        scope.startChantierAutomatique = () => {
          gaDomUtils.showGlobalLoader();
          scope.currentModel.previsionTableCassandra = HpoCarteAppFactory.getAppFactory().getPrevisionTableName(
            scope.currentModel.info.IDENTIFIANT_CALAGE,
            scope.currentModel.info.IDENTIFIANT
          );
          scope.currentModel.identifiantPrevision = scope.currentModel.info.IDENTIFIANT;
          scope.currentModel.createUser = $rootScope.xgos.user.login;
          HpoChantiersServices.createChantierAutomatique(
            scope.currentModel,
            scope.ftijeudonnee.uid,
            scope.ftihistory.uid,
            scope.fticalage.uid,
            scope.ftiprevision.uid).then(
              function (res) {
                try {
                  if (res.data && res.status) {
                    AlertHpoFactory.getSimpleSuccess(
                      $filter('translate')('hpo.common.success')
                    );
                    $rootScope.$broadcast('inititaliseApplicationBranch');
                  } else {
                    AlertHpoFactory.showErrorMessage(res);
                  }
                } catch (e) {
                  console.error(e.stack);
                }
                gaDomUtils.hideGlobalLoader();
              },
              function (res) {
                gaDomUtils.hideGlobalLoader();
                AlertHpoFactory.showErrorMessage(res);
              });
        }

        scope.refreshData = function () {
          $rootScope.$broadcast('reloadDatatable', scope.ftiChantierAutomatique.uid);
        };

        scope.editChantier = function(obj) {
          if (obj) {
            scope.chantierElement = angular.copy(obj.properties);

            var dialog = ngDialog.open({
                    template:
                      'js/XG/widgets/hpoapp/model/views/dialog/hpo.model.chantier_automatique.info.html',
                    className:
                      'ngdialog-theme-plain width1100 nopadding miniclose',
                    scope: scope,
            });
          }
        }

        scope.datatableCalageCrudHpo = {
          update: { func: scope.editChantier },
          remove: true,
          extraActions: [
            {
              name: $filter('translate')('hpo.common.refresh'),
              class: 'btn-default margin-left-right pull-left',
              func: scope.refreshData,
              icon: 'fa-refresh',
              special: true,
            },
          ],
        };

        scope.buttonEditIcon = [
          {
            type: 'component',
            config: {
              name: 'button',
              click: ['crud_update'],
            },
            cfg: {
              icon: { name: 'pencil-square-o' },
              iconOrLabel: 'icon',
              size: 'btn-xs',
              style: 'btn-default cursorHelp',
              title: 'Editer le dossier',
            },
          },
        ];

        scope.redochantier = (obj) => {
          if (obj) {
            var callback = function (confirmed) {
              if (confirmed) {
                gaDomUtils.showGlobalLoader();
                HpoChantiersServices.reloadCreateChantierAutomatique(
                  scope.ftiChantierAutomatique.uid,
                  obj.id,
                  scope.ftijeudonnee.uid,
                  scope.ftihistory.uid,
                  scope.fticalage.uid,
                  scope.ftiprevision.uid,
                  $rootScope.xgos.user.login).then(
                    function (res) {
                      gaDomUtils.hideGlobalLoader();
                      if (res.data && res.status) {
                        AlertHpoFactory.getSimpleSuccess(
                          $filter('translate')('hpo.data.exchange.succes'),
                          $filter('translate')('hpo.model.chantierAutomatique.success'),
                          true
                        );
                      } else {
                        AlertHpoFactory.showErrorMessage(res);
                      }
                      scope.refreshData();
                    },
                    function (res) {
                      gaDomUtils.hideGlobalLoader();
                      AlertHpoFactory.showErrorMessage(res);
                      scope.refreshData();
                    });
              }
            }

            AlertHpoFactory.alertConfirmCallback(
              $filter('translate')('hpo.common.warning'),
              $filter('translate')('hpo.model.chantierAutomatique.confirm_rerun'),
              'warning',
              true,
              undefined,
              '#F50072',
              true,
              undefined,
              undefined,
              true,
              true,
              callback
            );
          }
        }

        scope.generateChantier = (obj) => {
          if (obj) {
            var callback = function (confirmed) {
              if (confirmed) {
                gaDomUtils.showGlobalLoader();
                HpoChantiersServices.generateChantierAutomatique(
                  scope.ftiChantierAutomatique.uid,
                  obj.id,
                  scope.ftijeudonnee.uid,
                  scope.ftihistory.uid,
                  scope.fticalage.uid,
                  scope.ftiprevision.uid,
                  scope.ftiChantiers.uid,
                  HpoCarteAppFactory.getInitProvider().getHpoConfig()).then(
                    function (res) {
                      gaDomUtils.hideGlobalLoader();
                      if (res.status) {
                        AlertHpoFactory.getSimpleSuccess(
                          $filter('translate')('hpo.data.exchange.succes'),
                          $filter('translate')('hpo.model.chantierAutomatique.success_generer'),
                          true
                        );
                        $timeout(function () {
                          $rootScope.$broadcast(
                            'reloadDatatable',
                            scope.ftiChantierAutomatique.uid
                          );
                          getExistingNames();
                        }, 1000);
                      } else {
                        AlertHpoFactory.showErrorMessage(res);
                      }
                      scope.refreshData();
                    },
                    function (res) {
                      gaDomUtils.hideGlobalLoader();
                      AlertHpoFactory.showErrorMessage(res);
                      scope.refreshData();
                    });
              }
            }

            AlertHpoFactory.alertConfirmCallback(
              $filter('translate')('hpo.common.warning'),
              $filter('translate')('hpo.model.chantierAutomatique.confirm_generer'),
              'warning',
              true,
              undefined,
              '#F50072',
              true,
              undefined,
              undefined,
              true,
              true,
              callback
            );
          }
        }
        scope.disableAnalyseButton = function(currentModel) {
          const areCriteriaUndefined = angular.isDefined(currentModel.criteria) &&
            (!angular.isDefined(currentModel.criteria.minimumunitlinearconstruction) ||
              !angular.isDefined(currentModel.criteria.maximumitlinearconstruction) ||
              (currentModel.optimizationcriteria.hazardwaterloss && !angular.isDefined(currentModel.criteria.columnpiezometrynetwork)) ||
              (currentModel.optimizationcriteria.hazardtrafic &&!angular.isDefined(currentModel.criteria.populationdensity)));

          const areConstraintsUndefined = angular.isDefined(currentModel.constraints) &&
            (!angular.isDefined(currentModel.constraints.totalconstructionlinear) ||
              !angular.isDefined(currentModel.constraints.percentageofadditionallinear) ||
              !angular.isDefined(currentModel.constraints.defaultgeneratedlinear)||
              !angular.isDefined(currentModel.constraints.radiusDisjointed)||
              !angular.isDefined(currentModel.constraints.thresholdDegradation));
          if ((scope.existingNames && scope.existingNames.indexOf(currentModel.namechantierautomatique) !== -1) ||
              !angular.isDefined(currentModel.info) || !angular.isDefined(currentModel.namechantierautomatique) ||
              areCriteriaUndefined || areConstraintsUndefined ) {
            return true;
          } else {
            return false;
          }
        };

        scope.dataVisChantierAuto = (obj) => {
          scope.dataVisChantierAuto = obj;
          scope.typeDataVis = "chantierAuto";
          ngDialog.open({
            template:
              'js/XG/widgets/hpoapp/model/views/dialog/hpo.model.chantierauto.statistique.html',
            className:
              'ngdialog-theme-plain width100 nopadding miniclose',
            scope: scope,
          });
        }

        scope.exportResults = (obj) => {
          HpoChantiersServices.exportResults(obj.properties.IDENTIFIANT_PREVISION, obj.properties.IDENTIFIANT);
        }

        scope.buttonSpecialActions = [
          {
            class: 'btn btn-success btn-xs',
            icone: 'fa fa-play',
            text: $filter('translate')('hpo.model.chantierAutomatique.rerun'),
            callFunction: scope.redochantier,
            disableFunc: function (obj) {
              if (
                !obj ||
                !obj.properties ||
                !obj.properties.STATUS ||
                obj.properties.STATUS === 'RUNNING'
              )
                return true;
              else return false;
            },
          },
          {
            class: 'btn btn-warning btn-xs',
            icone: 'fa fa-forward',
            text: $filter('translate')('hpo.model.chantierAutomatique.generate'),
            callFunction: scope.generateChantier,
            disableFunc: function (obj) {
              if (
                !obj ||
                !obj.properties ||
                !obj.properties.PROGRESSION == 100 ||
                obj.properties.STATUS !== 'FINISHED'
              )
                return true;
              else return false;
            },
          },
          {
            class: 'btn btn-primary btn-xs',
            icone: 'fa fa-bar-chart',
            text: $filter('translate')('hpo.admin.dashBoardAutomatique.dataVis'),
            callFunction: scope.dataVisChantierAuto,
            disableFunc: function (obj) {
              if (
                !obj ||
                !obj.properties ||
                !obj.properties.PROGRESSION == 100 ||
                obj.properties.STATUS !== 'FINISHED'
              )
                return true;
              else return false;
            },
          },
          {
            class: 'btn btn-default btn-xs',
            icone: 'fa fa-download',
            text: $filter('translate')('hpo.admin.dashBoardAutomatique.exportResults'),
            callFunction: scope.exportResults,
            disableFunc: function (obj) {
              if (
                !obj ||
                !obj.properties ||
                !obj.properties.PROGRESSION == 100 ||
                obj.properties.STATUS !== 'FINISHED'
              )
                return true;
              else return false;
            },
          }
        ];

        scope.getExistingprevision();
      },
    };
  };

  constructionAutomatiqueHpo.$inject = [
    'HpoChantiersServices',
    'HpoCarteAppFactory',
    'QueryFactory',
    'AlertHpoFactory',
    'gaDomUtils',
    '$filter',
    '$rootScope',
    '$timeout',
    'ngDialog',
    'FeatureTypeFactory'
  ];
  return constructionAutomatiqueHpo;
});
