'use strict';
define(function() {
  var IndigauUserAppFactory = function(
    $filter,
    $rootScope,
    CarteInitProvider,
    extendedNgDialog,
    itvSoumfactory,
    itvSoumfactory2,
    ConfigFactory,
    $timeout,
    FeatureTypeFactory,
    $q
  ) {
    var soumissionScope;
    function closeItvSoumission() {
      if (
        soumissionScope != undefined &&
        soumissionScope.itvSoumissionDialog != undefined
      ) {
        soumissionScope.itvSoumissionDialog.close();
        soumissionScope.itvSoumissionDialog = undefined;
      }
    }

    function zoomToNetwork(scope, network) {
      if (!$rootScope.xgos.getMapAppMap) {
        $timeout(function() {
          zoomToNetwork(scope, network);
        }, 500);
        return;
      }
      var map = $rootScope.xgos.getMapAppMap();
      var ftiUid = network.visibleEdgesTypes[0].uid;
      FeatureTypeFactory.getExtent(
        ftiUid,map.getView().getProjection().getCode()
      ).then((res) => {
        var bbox = res.data;
        //const mapElement = document.getElementById('hpo-map');
        //const size = [mapElement.offsetWidth, mapElement.offsetHeight];
        const size = map.getSize();
        map.getView().fit(bbox, size);
      },
      (data) => {
        require('toastr').info(data);
      }
      );
    }

    function getItvConfig(scope) {
      let defer = $q.defer();
      scope.ConfigName = 'indigauItvCfg';
      itvSoumfactory.getConf('indigauItvCfg').then((conf) => {
        scope.conf = conf;
        defer.resolve();
      });
      return defer.promise;
    }

    function openItvSoumission(scope) {
      getItvConfig(scope).then(function() {
        ConfigFactory.get('main', 'indigauNetworkCfg').then(function(res) {
          if (res.data == '' || res.data.visibleEdgesTypes.length == 0) {
            swal({
              type: 'error',
              title: $filter('translate')('indigau.common.no_network'),
              text: '',
            });
          } else {
            soumissionScope = scope;
            scope.mode = localStorage.mode;
            scope.appType = $rootScope.xgos.sector;
            scope.itvSoumissionDialog = extendedNgDialog.open({
              template:
                'js/XG/widgets/mapapp/LITV/views/soumission/soumission.html',
              className:
                'ngdialog-theme-plain width600 max-heigth550 nopadding miniclose itvsoum',
              closeByDocument: false,
              scope: scope,
              draggable: {
                title: $filter('translate')('itv.create'),
              },
              preCloseCallback: function() {
                var map = $rootScope.xgos.getMapAppMap();
                d3.select('.svgitv')
                  .selectAll('*')
                  .remove();
                angular.element('#details').empty();
                angular.element('.detailtablesec .ng-table-pager').remove();
                itvSoumfactory2.getitvoperationalLayers()
                  .forEach(function(featureLayer) {
                    map.getLayers().forEach(function(Layer) {
                      if (
                        Layer.getProperties().name ==
                        featureLayer.getProperties().name
                      ) {
                        map.removeLayer(Layer);
                      }
                    });
                  });
                itvSoumfactory2.clearoriginsourcecanal();
                itvSoumfactory2.clearitvoperationalLayers();
                $('#closePanel').click();
                map.removeInteraction(scope.$$childHead.pointer);
              },
            });
            zoomToNetwork(scope, res.data);
          }
        });
      });
    }

    function openItvSoumissionEnMasse(scope) {
      getItvConfig(scope).then(function() {
        ConfigFactory.get('main', 'indigauNetworkCfg').then(function(res) {
          if (res.data == '' || res.data.visibleEdgesTypes.length == 0) {
            swal({
              type: 'error',
              title: $filter('translate')('indigau.common.no_network'),
              text: '',
            });
          } else {
            soumissionScope = scope;
            scope.mode = localStorage.mode;
            scope.appType = $rootScope.xgos.sector;
            scope.itvSoumissionDialog = extendedNgDialog.open({
              template:
                'js/XG/widgets/mapapp/LITV/views/soumissionEnMasse/soumissionEnMasse.html',
              className:
                'ngdialog-theme-plain width700 heigth500 nopadding miniclose itvsoum',
              closeByDocument: false,
              scope: scope,
              draggable: {
                title: $filter('translate')('itv.create'),
              },
              preCloseCallback: function() {
                var map = $rootScope.xgos.getMapAppMap();
                d3.select('.svgitv')
                  .selectAll('*')
                  .remove();
                angular.element('#details').empty();
                angular.element('.detailtablesec .ng-table-pager').remove();
                itvSoumfactory2.getitvoperationalLayers()
                  .forEach(function(featureLayer) {
                    map.getLayers().forEach(function(Layer) {
                      if (
                        Layer.getProperties().name ==
                        featureLayer.getProperties().name
                      ) {
                        map.removeLayer(Layer);
                      }
                    });
                  });
                itvSoumfactory2.clearoriginsourcecanal();
                itvSoumfactory2.clearitvoperationalLayers();
                $('#closePanel').click();
                map.removeInteraction(scope.$$childHead.pointer);
              },
            });
            zoomToNetwork;
            scope, res.data;
          }
        });
      });
    }
    function getUser() {
      return CarteInitProvider.getUser();
    }

    function getUserRoles() {
      var user = CarteInitProvider.getUser();
      return user.roles;
    }

    function isKisRootUser() {
      var user = CarteInitProvider.getUser();
      var roles = user.roles;
      var rolesNames = roles.map(function(x) {
        return x.name;
      });
      return user.name === 'root';
    }

    function isRootUser() {
      var user = CarteInitProvider.getUser();
      var roles = user.roles;
      var rolesNames = roles.map(function(x) {
        return x.name;
      });
      return rolesNames.indexOf('rootUser') !== -1;
    }

    function isSuperRootUser() {
      var user = CarteInitProvider.getUser();
      var roles = user.roles;
      var rolesNames = roles.map(function(x) {
        return x.name;
      });
      return rolesNames.indexOf('sRootUser') !== -1;
    }

    function isMulticriteriaAnalyst() {
      var user = CarteInitProvider.getUser();
      var roles = user.roles;
      var rolesNames = roles.map(function(x) {
        return x.name;
      });
      return rolesNames.indexOf('MulticriteriaAnalyst') !== -1;
    }

    function getMulticritereSubOptions() {
      var multicritereComposantFilter = {
        label: 'hpo.multicritere.filter.title',
        icon: 'filter',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/multicritere/hpo.multicritere.filter.tpl.html',
        visible: true,
        description: '',
      };
      var multicritereParameters = {
        label: 'hpo.multicritere.parameters.title',
        icon: 'cog',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/multicritere/hpo.multicritere.parameters.tpl.html',
        visible: true,
        description: '',
      };
      var multicritereConstruct = {
        label: 'hpo.multicritere.construct.title',
        icon: 'plus',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/multicritere/hpo.multicritere.construct.tpl.html',
        visible: true,
        description: '',
      };
      var multicritereAnalyse = {
        label: 'hpo.multicritere.analyse.title',
        icon: 'edit',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/multicritere/hpo.multicritere.analyse.tpl.html',
        visible: true,
        description: '',
      };
      var multicritereIndicateur = {
        label: 'hpo.multicritere.indicateur.title',
        icon: 'plus-square',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/multicritere/hpo.multicritere.indicateur.tpl.html',
        visible: true,
        description: '',
      };
      var multicritereCompare = {
        label: 'hpo.multicritere.compare.title',
        icon: 'line-chart',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/multicritere/hpo.multicritere.compare.tpl.html',
        visible: true,
        description: '',
      };
      var multicritereRetenu = {
        label: 'hpo.multicritere.retenu.title',
        icon: 'mouse-pointer',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/multicritere/hpo.multicritere.retenu.tpl.html',
        visible: true,
        description: '',
      };

      return [
        multicritereComposantFilter,
        multicritereParameters,
        multicritereConstruct,
        multicritereIndicateur,
        multicritereAnalyse,
        multicritereCompare,
        multicritereRetenu,
      ];
    }

    function getChantiersSubOptions() {
      var multicritereCorrespondance = {
        label: 'hpo.multicritere.correspondance.title',
        icon: 'arrows-h',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/multicritere/hpo.multicritere.correspondance.tpl.html',
        visible: true,
        description: '',
      };

      var chantiersCreate = {
        label: 'hpo.chantiers.creation.title',
        icon: 'plus',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/chantiers/chantiers.tpl.html',
        visible: true,
        description: '',
      };

      var chantiersListe = {
        label: 'hpo.chantiers.liste.title',
        icon: 'list',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/chantiers/liste.chantiers.tpl.html',
        visible: true,
        description: '',
      };

      return [multicritereCorrespondance, chantiersCreate, chantiersListe];
    }

    let getagingModelSubOptions = () => {
      return [
        {
          label: 'indigau.agingModel.dataSet.title',
          icon: 'list',
          template: 'js/XG/widgets/hpoapp/main/views/templates/model/hpo.model.jeu.tpl.html',
          visible: true,
          description: '',
        },
        {
          label: 'indigau.agingModel.standardization.title',
          icon: 'magic',
          template:
            'js/XG/widgets/hpoapp/main/views/templates/data/hpo.data.standardisation.tpl.html',
          visible: true,
          description: '',
        },
        {
          label: 'indigau.agingModel.calibrationModel.title',
          icon: 'edit',
          template:
            'js/XG/widgets/hpoapp/main/views/templates/model/hpo.model.calage.tpl.html',
          visible: true,
          description: '',
        }
      ]
    }

    function getITVsSubOptions() {
      return [
        {
          label: 'indigau.itv.config.title',
          icon: 'upload',
          template: 'js/XG/widgets/mapapp/LITV/views/itvConfig.html',
          visible: true,
          description: '',
        },

        {
          label: 'indigau.itv.import.title',
          icon: 'upload',
          template: 'js/XG/widgets/indigauapp/main/views/itv/itvimport.html',
          visible: true,
          description: '',
          initialActions: [openItvSoumission],
          toCallOnClose: closeItvSoumission,
          withMap: true,
        },

        {
          label: 'indigau.itv.importenmasse.title',
          icon: 'upload',
          template:
            'js/XG/widgets/indigauapp/main/views/itv/itvimportenmasse.html',
          visible: true,
          description: '',
          initialActions: [openItvSoumissionEnMasse],
          toCallOnClose: closeItvSoumission,
          withMap: true,
        },

        {
          label: 'indigau.itv.list.title',
          icon: 'th-list',
          template: 'js/XG/widgets/indigauapp/main/views/itv/itvliste.html',
          visible: true,
          description: '',
          scopeParameters: [
            {
              name: 'selectedAttributes',
              value: [
                'brchtnums',
                'creationdate',
                'realisationdateheure',
                'date_rerau',
                'nb_part',
                'collnb',
                'collmatchingnb',
                'collassociatednb',
                'brchtnb',
                'brchtmatchingnb',
                'brchtassociatednb',
                'regnb',
                'regmatchingnb',
                'regassociatednb',
                'collconcerne',
                'brchtconcerne',
                'file_language',
              ],
            },
          ],
        },

        {
          label: 'indigau.itv.refreshrerau.title',
          icon: 'refresh',
          template:
            'js/XG/widgets/indigauapp/main/views/itv/itvrefreshrerau.html',
          visible: true,
          description: '',
        },
      ];
    }

    function getNavigationHpo() {
      var navigations = [];

      var title = {
        main_title: 'hpo.home.title',
        label: 'hpo.home.title',
        icon: 'home',
        template:
          'js/XG/widgets/indigauapp/main/views/templates/hpo.home.tpl.html',
        visible: true,
        description: '',
      };

      var admin = {
        main_title: 'hpo.admin.title',
        label: 'hpo.admin.title',
        icon: 'cogs',
        template:
          'js/XG/widgets/indigauapp/main/views/templates/hpo.admin.tpl.html',
        visible: true,
        description: '',
      };

      var dataCheck = {
        label: 'hpo.data.check.title',
        icon: 'table',
        template:
          'js/XG/widgets/indigauapp/main/views/templates/hpo.data.check.tpl.html',
        visible: true,
        description: '',
      };
      var dataExchange = {
        label: 'hpo.data.exchange.title',
        icon: 'exchange',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/data/hpo.data.exchange.tpl.html',
        visible: true,
        description: '',
      };
      var dataPrepare = {
        label: 'hpo.data.prepare.title',
        icon: 'pencil',
        template:
          'js/XG/widgets/hpoapp/main/views/templates/data/hpo.data.prepare.tpl.html',
        visible: true,
        description: '',
      };

      var data = {
        main_title: 'hpo.data.title',
        isCollapsed: true,
        activeSub: false,
        icon: 'database',
        subs: [],
      };
      let agingModel = {
        main_title: 'indigau.agingModel.title',
        isCollapsed: true,
        activeSub: false,
        icon: 'server',
        subs: getagingModelSubOptions(),
      };
      var ITVs = {
        main_title: 'indigau.itv.title',
        isCollapsed: true,
        activeSub: false,
        icon: 'video-camera',
        subs: getITVsSubOptions(),
      };

      var multicritere = {
        main_title: 'hpo.multicritere.title',
        isCollapsed: true,
        activeSub: false,
        icon: 'code-fork',
        subs: getMulticritereSubOptions(),
      };

      var chantiers = {
        main_title: 'hpo.chantiers.title',
        isCollapsed: true,
        activeSub: false,
        icon: 'cubes',
        subs: getChantiersSubOptions(),
      };

      var carte = {
        main_title: 'mapv2.carte.title',
        label: 'mapv2.carte.title',
        icon: 'map',
        template:
          'js/XG/widgets/indigauapp/main/views/templates/hpo.carte.tpl.html',
        visible: true,
        description: '',
      };

      data.subs = data.subs.concat([
        dataCheck,
        dataExchange,
        dataPrepare,
      ]);

      navigations = navigations.concat([title]);
      if (isSuperRootUser() || isRootUser() || isKisRootUser())
        navigations.push(admin);
      navigations.push(data);
      // menu model de vieillissement
      navigations.push(agingModel);
      //-- Menu ITV
      navigations.push(ITVs);

      if (
        CarteInitProvider.hasMulticritere() &&
        (isMulticriteriaAnalyst() ||
          isSuperRootUser() ||
          isRootUser() ||
          isKisRootUser())
      ) {
        navigations.push(multicritere);
        navigations.push(chantiers);
      }
      navigations.push(carte);
      return navigations;
    }

    return {
      getUser: getUser,
      getUserRoles: getUserRoles,
      isRootUser: isRootUser,
      getNavigationHpo: getNavigationHpo,
    };
  };
  IndigauUserAppFactory.$inject = [
    '$filter',
    '$rootScope',
    'CarteInitProvider',
    'extendedNgDialog',
    'itvSoumFactory',
    'itvSoumFactory2',
    'ConfigFactory',
    '$timeout',
    'FeatureTypeFactory',
    '$q'
  ];
  return IndigauUserAppFactory;
});
