'use strict';
define(function() {
  var adminIndigau = function(
    AlertHpoFactory,
    FeatureTypeFactory,
    IndigauAppFactory,
    $window,
    EditFactory,
    $rootScope,
    $filter,
    ngDialog,
    $timeout,
    ParametersFactory,
    gaDomUtils,
    HpoAppServices,
    ImportExportFactory,
    licenceFactory,
    CarteInitProvider,
    ConfigFactory,
    $q,
    HpoCarteAppFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/indigauapp/home_admin_data/views/directives/admin_indigau.html',
      restrict: 'EA',
      link: function(scope) {
        scope.configureName =
          IndigauAppFactory.getAppname() + '_' + 'CarteAdministrationConfig';
        scope.indigau = true;
        scope.hpo = {
          pages: [
            {
              label: 'hpo.admin.datastore',
            },
            {
              label: 'hpo.admin.components',
            },
            {
              label: 'hpo.admin.basemap',
            },
            {
              label: 'hpo.data.analyse.title',
            },
            {
              label: 'hpo.admin.home.title',
            },
            {
              label: 'indigau.admin.network',
            },
            {
              label: 'indigau.admin.choixRegleDensite',
            },
          ],
          activeTab: 0,
          cfg: CarteInitProvider.getHpoConfig(),
        };
        scope.tabs = [
          {
            title: 'hpo.data.analyse.newanalyse',
          },
          {
            title: 'hpo.data.analyse.dashboardconfig',
          },
        ];
        scope.tabs.activeTab = 0;
        scope.configName =
          HpoCarteAppFactory.getAppFactory().getAppname() +
          '_' +
          'HpoAnalyseDataConfig';
        if (scope.hpo.cfg && scope.hpo.cfg.multicritere) {
          scope.hpo.pages.push({
            label: 'mapv2.admin.configurationpage.componentshpo',
          });
        }
        scope.description1 = $filter('translate')(
          'mapv2.admin.configurationpage.description'
        );
        scope.description2 = $filter('translate')(
          'mapv2.admin.configurationpage.description'
        );

        if (scope.hpo.cfg && !scope.hpo.cfg.currentResources) {
          scope.hpo.cfg.currentResources = [];
          scope.currentResources = [];
        } else {
          scope.currentResources = angular.copy(scope.hpo.cfg.currentResources);
        }

        var saveInitConf = function() {
          ConfigFactory.add(scope.hpo.cfg, 'main', 'appconfig').then(
            function(res) {
              if (res && res.data) {
                CarteInitProvider.setHpoConfig(scope.hpo.cfg);
                CarteInitProvider.initialiseApplication().then(
                  function() {
                    IndigauAppFactory.initFactory();
                    gaDomUtils.hideGlobalLoader();
                  },
                  function() {
                    gaDomUtils.hideGlobalLoader();
                  }
                );
              } else {
                gaDomUtils.hideGlobalLoader();
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        scope.calculheight =
          angular.element('.xgos_content').height() -
          angular.element('#xgos_nav').height() -
          angular.element('.description').height() -
          50 +
          'px';

        scope.calculheightSpecial =
          angular.element('.xgos_content').height() -
          angular.element('#xgos_nav').height() -
          25 +
          'px';

        scope.xgos = $rootScope.xgos;
        scope.reinitApplicationConfig = function() {
          var callback = function(isconfirm) {
            if (isconfirm) {
              gaDomUtils.showGlobalLoader();
              IndigauAppFactory.updateConfig(scope.hpo.cfg, true).then(
                function(res) {
                  if (res && res.data) {
                    scope.hpo.cfg = res.data;
                    CarteInitProvider.setHpoConfig(scope.hpo.cfg);
                    CarteInitProvider.initialiseApplication().then(
                      function() {
                        IndigauAppFactory.initFactory();
                        AlertHpoFactory.getSimpleSuccess(
                          $filter('translate')('hpo.data.exchange.succes'),
                          $filter('translate')('hpo.common.reinitapplication'),
                          false
                        );
                        gaDomUtils.hideGlobalLoader();
                      },
                      function() {
                        gaDomUtils.hideGlobalLoader();
                      }
                    );
                  } else {
                    gaDomUtils.hideGlobalLoader();
                  }
                },
                function(res) {
                  AlertHpoFactory.showErrorMessage(res);
                  gaDomUtils.hideGlobalLoader();
                }
              );
              try {
                scope.$apply();
              } catch(err) {}
            }
          };
          var message =
            $filter('translate')('hpo.common.reinitapp') +
            '. ' +
            $filter('translate')('hpo.common.sur');
          AlertHpoFactory.alertConfirmCallback(
            $filter('translate')('hpo.common.warning'),
            message,
            'warning',
            true,
            undefined,
            '#F50072',
            true,
            undefined,
            undefined,
            true,
            true,
            callback
          );
        };

        /* Ajout de composant et des statistiques
         */
        if (scope.hpo.cfg && !scope.hpo.cfg.addedstatistics)
          scope.hpo.cfg.addedstatistics = [];
        scope.hideCompnents = {};

        scope.baseMapDataVis = [
          {
            name: "light_all",
            alias: "Light with All Labels"
          },
          {
            name: "dark_all",
            alias: "Dark with All Labels"
          },
          {
            name: "light_nolabels",
            alias: "Light without Labels"
          },
          {
            name: "light_only_labels",
            alias: "Light Labels Only"
          },
          {
            name: "dark_nolabels",
            alias: "Dark without Labels"
          },
          {
            name: "dark_only_labels",
            alias: "Dark Labels Only"
          },
          {
            name: "rastertiles/voyager",
            alias: "Voyager with Labels"
          },
          {
            name: "rastertiles/voyager_nolabels",
            alias: "Voyager without Labels"
          },
          {
            name: "rastertiles/voyager_only_labels",
            alias: "Voyager Labels Only"
          },
          {
            name: "rastertiles/voyager_labels_under",
            alias: "Voyager Labels Under"
          }, 
          {
            name:"osm",
            alias:"OSM"
          }
        ];
        if(!scope.hpo.cfg.baseMap){
          scope.hpo.cfg.baseMap = 'light_all';
        }
        if(!scope.hpo.cfg.baseMap){
          scope.hpo.cfg.baseMap = 'toner-lite';
        }

        scope.addStat = function(element, idx) {
          if (element) {
            scope.statistic = angular.copy(element);
            scope.statistic.idx = idx;
            scope.isNew = false;
          } else {
            scope.statistic = {};
            scope.idx = undefined;
            scope.isNew = true;
          }
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/home_admin_data/views/dialog/hpo.data.addstatistic.html',
            className: 'ngdialog-theme-plain width800 nopadding miniclose',
            scope: scope,
          });
          dialog.then(function(data) {
            if (data) {
              if (angular.isDefined(data.idx)) {
                var idx = data.idx;
                delete data.idx;
                scope.hpo.cfg.addedstatistics[idx] = angular.copy(data);
                AlertHpoFactory.successUpdate();
              } else {
                scope.hpo.cfg.addedstatistics.push(angular.copy(data));
                AlertHpoFactory.successAdd();
              }
            }
          });
        };

        scope.removeStat = function(idx) {
          var callback = function(isconfirm) {
            if (isconfirm) {
              scope.hpo.cfg.addedstatistics.splice(idx, 1);
              AlertHpoFactory.successDelete();
              try {
                scope.$apply();
              } catch(err) {}
            }
          };
          var message =
            $filter('translate')('hpo.common.removestat') +
            '. ' +
            $filter('translate')('hpo.common.sur');
          AlertHpoFactory.alertConfirmCallback(
            $filter('translate')('hpo.common.warning'),
            message,
            'warning',
            true,
            undefined,
            '#F50072',
            true,
            undefined,
            undefined,
            true,
            true,
            callback
          );
        };

        /* Conf base pages
         */
        var refreshFtis = () => {
          scope.ftis = [];

          scope.ftis = HpoCarteAppFactory.getAppFactory().getFeatureTypes('config');
        };
        refreshFtis();

        /**
         * Config analyse multicritere
         */
        var checkRelationChantiers = function(data) {
          var relation;
          var uid = data.component.uid;
          var exists = false;
          for (var i = 0; i < ftiChantiers.relations.length; i++) {
            var rel = ftiChantiers.relations[i];
            if (
              rel.type === 'REL_NM' &&
              rel.idStart === ftiChantiers.uid &&
              rel.idEnd === uid
            ) {
              exists = true;
            }
          }
          if (!exists) {
            relation = {
              type: 'REL_NM',
              relationType: null,
              disabled: false,
              name: 'RELATION_CHANTIERS_' + data.component.name,
              componentStart: ftiChantiers.name,
              componentEnd: data.component.name,
              alias: 'relation chantiers et ' + data.component.alias,
              idStart: ftiChantiers.uid,
              idEnd: data.component.uid,
            };
          }
          return relation;
        };

        var checkAttributesRequired = function(data) {
          var response = false;
          var attributes = Object.keys(data.attributes).map(function(x) {
            if(x !== "date_abandon"){
              return data.attributes[x].name;
            }
          });
          data.component.attributes.map(function(x) {
            if (attributes.indexOf(x.name) !== -1 && x.isNillable) {
              response = true;
              x.isNillable = false;
            }
          });
          return response;
        };

        var addElement = function(data) {
          var treateddata = {
            id: Math.random(),
            uid: data.component.uid,
            alias: data.component.alias,
            identifiant: data.attributes.identifiant.name,
            date_de_pose: data.attributes.date_de_pose.name,
            format_date_de_pose: data.format_date_pose,
            date_abandon: angular.isDefined(data.attributes.date_abandon)?data.attributes.date_abandon.name:'',
            format_date_abandon: data.format_date_abandon,
            materiau: data.attributes.materiau.name,
            diametre: data.attributes.diametre.name,
            longueur: data.attributes.longueur.name,
            commune: data.attributes.commune.name,
            regard_uid: data.component_regard.uid,
            regard_alias: data.component_regard.alias,
            regard_identifiant: data.attributes_regard.name,
            itv: angular.isDefined(data.itv) && angular.isDefined(data.itv.uid)?data.itv.uid: "",
          };
          scope.currentResources.push(treateddata);
          scope.hpo.cfg.currentResources.push(treateddata);
          gaDomUtils.showGlobalLoader();
          ConfigFactory.add(scope.hpo.cfg, 'main', 'appconfig').then(
            function(res) {
              if (res && res.data) {
                HpoCarteAppFactory.getInitProvider().setHpoConfig(
                  scope.hpo.cfg
                );
                HpoCarteAppFactory.getInitProvider()
                  .initialiseApplication()
                  .then(
                    function() {
                      HpoCarteAppFactory.getAppFactory().initFactory();
                      gaDomUtils.hideGlobalLoader();
                    },
                    function() {
                      gaDomUtils.hideGlobalLoader();
                    }
                  );
              } else {
                gaDomUtils.hideGlobalLoader();
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        var ftiChantiers = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'chantiers'
        )[0];
        var ngdialog;
        scope.addComponent = function() {
          scope.newItem = true;
          scope.configuser = {};
          scope.selected_resource = {};
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/indigauapp/home_admin_data/views/dialog/indigau.admin.component.html',
            className:
              'ngdialog-theme-plain width1100 minheight500 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
          });
          dialog.then(function(data) {
            var relationChantiers = checkRelationChantiers(data);
            if (relationChantiers || checkAttributesRequired(data)) {
              var sendata = {};
              sendata[data.component.uid] = null;
              sendata[ftiChantiers.uid] = null;
              if (relationChantiers)
                sendata[ftiChantiers.uid] = relationChantiers;
              gaDomUtils.showGlobalLoader();
              HpoCarteAppFactory.getAppFactory()
                .addRelationAdmin(data.component.uid, ftiChantiers.uid, sendata)
                .then(
                  function(res) {
                    gaDomUtils.hideGlobalLoader();
                    addElement(data);
                  },
                  function(res) {
                    gaDomUtils.hideGlobalLoader();
                    AlertHpoFactory.showErrorMessage(res);
                  }
                );
            } else {
              addElement(data);
            }
          });
        };

        var updateCon = function(data, treateddata) {
          var idx = scope.currentResources
            .map(function(x) {
              return x.id;
            })
            .indexOf(data.id);
          if (~idx) scope.currentResources[idx] = treateddata;
          idx = scope.hpo.cfg.currentResources
            .map(function(x) {
              return x.id;
            })
            .indexOf(data.id);
          if (~idx) scope.hpo.cfg.currentResources[idx] = treateddata;
          gaDomUtils.showGlobalLoader();
          ConfigFactory.add(scope.hpo.cfg, 'main', 'appconfig').then(
            function(res) {
              if (res && res.data) {
                HpoCarteAppFactory.getInitProvider().setHpoConfig(
                  scope.hpo.cfg
                );
                HpoCarteAppFactory.getInitProvider()
                  .initialiseApplication()
                  .then(
                    function() {
                      HpoCarteAppFactory.getAppFactory().initFactory();
                      gaDomUtils.hideGlobalLoader();
                    },
                    function() {
                      gaDomUtils.hideGlobalLoader();
                    }
                  );
              } else {
                gaDomUtils.hideGlobalLoader();
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        scope.updateComponent = function() {
          scope.newItem = false;
          scope.configuser = angular.copy(scope.selected_resource);
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/indigauapp/home_admin_data/views/dialog/indigau.admin.component.html',
            className:
              'ngdialog-theme-plain width1100 minheight500 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
          });
          dialog.then(function(data) {
            var treateddata = {
              id: data.id,
              uid: data.component.uid,
              alias: data.component.alias,
              identifiant: data.attributes.identifiant.name,
              date_de_pose: data.attributes.date_de_pose.name,
              format_date_de_pose: data.format_date_pose,
              date_abandon: angular.isDefined(data.attributes.date_abandon)?data.attributes.date_abandon.name:'',
              format_date_abandon: data.format_date_abandon,
              materiau: data.attributes.materiau.name,
              diametre: data.attributes.diametre.name,
              longueur: data.attributes.longueur.name,
              commune: data.attributes.commune.name,
              regard_uid: data.component_regard.uid,
              regard_alias: data.component_regard.alias,
              regard_identifiant: data.attributes_regard.name,
              itv: angular.isDefined(data.itv) && angular.isDefined(data.itv.uid)?data.itv.uid: "",
            };
            var relationChantiers = checkRelationChantiers(data);
            if (relationChantiers || checkAttributesRequired(data)) {
              var sendata = {};
              sendata[data.component.uid] = null;
              sendata[ftiChantiers.uid] = null;
              if (relationChantiers)
                sendata[ftiChantiers.uid] = relationChantiers;
              gaDomUtils.showGlobalLoader();
              HpoCarteAppFactory.getAppFactory()
                .addRelationAdmin(data.component.uid, ftiChantiers.uid, sendata)
                .then(
                  function(res) {
                    gaDomUtils.hideGlobalLoader();
                    updateCon(data, treateddata);
                  },
                  function(res) {
                    gaDomUtils.hideGlobalLoader();
                    AlertHpoFactory.showErrorMessage(res);
                  }
                );
            } else {
              updateCon(data, treateddata);
            }
          });
        };

        var saveInitConf = function() {
          ConfigFactory.add(scope.hpo.cfg, 'main', 'appconfig').then(
            function(res) {
              if (res && res.data) {
                HpoCarteAppFactory.getInitProvider().setHpoConfig(
                  scope.hpo.cfg
                );
                HpoCarteAppFactory.getInitProvider()
                  .initialiseApplication()
                  .then(
                    function() {
                      HpoCarteAppFactory.getAppFactory().initFactory();
                      gaDomUtils.hideGlobalLoader();
                    },
                    function() {
                      gaDomUtils.hideGlobalLoader();
                    }
                  );
              } else {
                gaDomUtils.hideGlobalLoader();
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        scope.removeComponent = function(v) {
          if (angular.isDefined(v)) {
            var data = scope.currentResources[v];
            scope.removedData = angular.copy(scope.currentResources[v]);
            var idx = scope.hpo.cfg.currentResources
              .map(function(x) {
                return x.id;
              })
              .indexOf(data.id);
            if (~idx) scope.hpo.cfg.currentResources.splice(idx, 1);
            scope.currentResources.splice(v, 1);

            var callback = function(isconfirm) {
              if (isconfirm) {
                gaDomUtils.showGlobalLoader();
                HpoCarteAppFactory.getAppFactory()
                  .removeFeaturesAdmin(
                    scope.removedData.uid,
                    scope.removedData.defail_uid,
                    scope.hpo.cfg.datastoreName
                  )
                  .then(
                    function(res) {
                      if (res && res.data && JSON.parse(res.data)) {
                        AlertHpoFactory.successDelete();
                        saveInitConf();
                      } else {
                        gaDomUtils.hideGlobalLoader();
                        AlertHpoFactory.failDelete();
                      }
                    },
                    function(res) {
                      AlertHpoFactory.showErrorMessage(res);
                      saveInitConf();
                    }
                  );
                try {
                  scope.$apply();
                } catch(err) {}
              } else {
                gaDomUtils.showGlobalLoader();
                saveInitConf();
              }
            };
            var message = $filter('translate')(
              'hpo.common.removeAllInformations'
            );
            AlertHpoFactory.alertConfirmCallback(
              $filter('translate')('hpo.common.warning'),
              message,
              'warning',
              true,
              undefined,
              '#F50072',
              true,
              undefined,
              undefined,
              true,
              true,
              callback
            );
          }
        };

        scope.save = function() {
          gaDomUtils.showGlobalLoader();
          ConfigFactory.add(scope.hpo.cfg, 'main', 'appconfig').then(
            function(res) {
              if (res && res.data) {
                HpoCarteAppFactory.getInitProvider().setHpoConfig(
                  scope.hpo.cfg
                );
                HpoCarteAppFactory.getInitProvider()
                  .initialiseApplication()
                  .then(
                    function() {
                      HpoCarteAppFactory.getAppFactory().initFactory();
                      AlertHpoFactory.getSimpleSuccess(
                        $filter('translate')('hpo.common.info'),
                        $filter('translate')('hpo.common.success'),
                        false,
                        'info'
                      );
                      gaDomUtils.hideGlobalLoader();
                    },
                    function() {
                      AlertHpoFactory.getSimpleSuccess(
                        $filter('translate')('hpo.common.info'),
                        $filter('translate')('hpo.error.data.updateconf'),
                        true,
                        'error'
                      );
                      gaDomUtils.hideGlobalLoader();
                    }
                  );
              } else {
                AlertHpoFactory.getSimpleSuccess(
                  $filter('translate')('hpo.common.info'),
                  $filter('translate')('hpo.error.data.updateconf'),
                  true,
                  'error'
                );
                gaDomUtils.hideGlobalLoader();
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        scope.editListCfg = {
          dataModule: 'hpo',
          resource_type: 'admin',
          cols: [
            'alias',
            'identifiant',
            'date_de_pose',
            'materiau',
            'diametre',
            'longueur',
          ],
          addFunction: scope.addComponent,
          editFunction: scope.updateComponent,
          removeFunction: scope.removeComponent,
          deleteResourceButton: true,
          dontShowLength: false,
          notAddMode: false,
          notPagination: false,
        };

        scope.calculheight =
          angular.element('.xgos_content').height() -
          angular.element('#xgos_nav').height() -
          angular.element('.description').height() -
          50 +
          'px';

        scope.calculheightSpecial =
          angular.element('.xgos_content').height() -
          angular.element('#xgos_nav').height() -
          25 +
          'px';
      },
    };
  };

  adminIndigau.$inject = [
    'AlertHpoFactory',
    'FeatureTypeFactory',
    'IndigauAppFactory',
    '$window',
    'EditFactory',
    '$rootScope',
    '$filter',
    'ngDialog',
    '$timeout',
    'ParametersFactory',
    'gaDomUtils',
    'HpoAppServices',
    'ImportExportFactory',
    'licenceFactory',
    'CarteInitProvider',
    'ConfigFactory',
    '$q',
    'HpoCarteAppFactory',
  ];
  return adminIndigau;
});
