'use strict';
define(function() {
  /*
   * Params :
   * map /
   */
  var imexMbtiles = function(
    mbtilesService,
    FeatureTypeFactory,
    $filter,
    gcStyleFactory,
    gaDomUtils,
    SelectManager,
    $interval,
    $rootScope,
    gcInteractions,
    SridFactory,
    processFactory,
    $location,
    ngDialog,
    gaUrlUtils,
    ngTableParams,
    gclayers,
    $timeout /*, geopackageService */
  ) {
    return {
      // TODO verif model
      templateUrl:
        'js/XG/widgets/mapapp/importExportMBTILES/views/importExportMBTILES.html',
      restrict: 'A',
      link: function(scope, element, attrs, ctrl) {
        var Level_zero = 156543.03390625;
        var zoom_levels = [];
        for (var i = 0; i < 40; i++) {
          zoom_levels.push(156543.03390625 / Math.pow(2, i));
        }

        scope.tabs = [
          {
            title: $filter('translate')('importExportMBTILES.export'),
          },
          {
            title: $filter('translate')('importExportMBTILES.process'),
          },
        ];

        scope.widgetName =
          'export-mbtiles-' + Math.floor(Math.random() * 10000000);
        scope.mbtiles = {
          ftis: [],
          applyFilter: false,
          bbox: {
            minx: undefined,
            miny: undefined,
            maxx: undefined,
            maxy: undefined,
          },
          fromCurrentSelection: false,
          ftiuids: {},
          activeTab: 0,
          version: '1.3.0',
          format: 'image/png',
          srid: 'EPSG:3857',
          minzoom: 0,
          maxzoom: 15,
          openstreetmap: false,
          transparent: $filter('translate')('common.yes'),
          runonbackground: true,
          zoominit: scope.map.getView().getZoom(),
          createboth: false,
        };

        scope.validName = function(name) {
          return /^[A-Za-z0-9-_]+$/.test(name);
        };

        scope.transparency = [
          $filter('translate')('common.yes'),
          $filter('translate')('common.no'),
        ];

        scope.srids = SridFactory.sridsList;

        function setExtent(extent) {
          scope.mbtiles.bbox = {
            minx: Math.round(extent[0] * 1000000) / 1000000,
            miny: Math.round(extent[1] * 1000000) / 1000000,
            maxx: Math.round(extent[2] * 1000000) / 1000000,
            maxy: Math.round(extent[3] * 1000000) / 1000000,
          };
          var extent3857 = ol.proj.transformExtent(
            extent,
            scope.mbtiles.srid,
            scope.map
              .getView()
              .getProjection()
              .getCode()
          );
          var polygon = ol.geom.Polygon.fromExtent(extent3857);
          var feature = new ol.Feature(polygon);
          try {
            scope.SelectionLayer.getSource().clear();
          } catch (e) {
            e.stack;
          }
          scope.SelectionLayer.getSource().addFeature(feature);
        }

        if (
          $rootScope.xgos &&
          $rootScope.xgos.mouseposition &&
          $rootScope.xgos.mouseposition.srid &&
          $rootScope.xgos.mouseposition.srid.name &&
          $rootScope.xgos.mouseposition.srid.name.indexOf('EPSG:') !== -1
        ) {
          scope.mbtiles.srid = $rootScope.xgos.mouseposition.srid.name;
          if ($rootScope.xgos.mouseposition.srid.description) {
            proj4.defs(
              $rootScope.xgos.mouseposition.srid.name,
              $rootScope.xgos.mouseposition.srid.description
            );
            scope.sriddescription =
              $rootScope.xgos.mouseposition.srid.description;
          }
        }

        var stop = $interval(function() {
          if (
            FeatureTypeFactory.resources.featuretypes &&
            FeatureTypeFactory.resources.featuretypes.length > 0
          ) {
            if (
              gclayers.getOperationalLayerg2c() &&
              gclayers.getOperationalLayerg2c().length > 0
            ) {
              scope.getFeatureFromCatalogue();
              $interval.cancel(stop);
            }
          }
        }, 3000);

        scope.getFeatureFromCatalogue = function() {
          scope.mbtiles.ftis = [];
          gclayers.getOperationalLayerg2c().map(function(x) {
            if (x.fti && x.fti.geographic && x.fti.name)
              scope.mbtiles.ftis.push({
                name: x.fti.name,
                alias: x.fti.alias,
                style: x.fti.defaultStyle,
                uid: x.fti.uid,
                opacity: x.opacity,
                cql_filter: x.cql_filter,
                selected: x.visible,
                type: 'g2c',
              });
          });
          gclayers.getOperationalLayerESRI().map(function(x) {
            if (x.fti && x.fti.geographic && x.fti.name)
              scope.mbtiles.ftis.push({
                name: x.fti.name,
                alias: x.fti.alias,
                style: x.fti.defaultStyle,
                uid: x.fti.uid,
                opacity: x.opacity,
                cql_filter: x.cql_filter,
                selected: x.visible,
                type: 'esri',
                wfs: x.fti.wfs,
                wms: x.fti.wms,
              });
          });
        };

        scope.initSelection = function() {
          scope.mbtiles.ftis.map(function(x) {
            x.selected = false;
          });
        };

        scope.getZoomFromMap = function(type) {
          switch (type) {
            case 'init':
              scope.mbtiles.zoominit = scope.map.getView().getZoom();
              break;
            default:
              scope.mbtiles.maxzoom = scope.map.getView().getZoom();
              break;
          }
        };

        scope.changedSrid = function(srid) {
          if (srid.indexOf('EPSG:') !== -1 && !ol.proj.get(srid))
            SridFactory.getbycode(srid).then(function(res) {
              scope.sriddescription = res.data;
              proj4.defs(srid, res.data);
            });
        };

        scope.getMapExtent = function() {
          var extent = scope.map.getView().calculateExtent(scope.map.getSize());
          var extentproj = ol.proj.transformExtent(
            extent,
            scope.map
              .getView()
              .getProjection()
              .getCode(),
            scope.mbtiles.srid
          );
          setExtent(extentproj);
          scope.mbtiles.fromCurrentSelection = false;
        };

        var dragBoxStyle = gcStyleFactory.getStyle('selectrectangle');
        scope.dragBox = new ol.interaction.DragBox({
          type: 'Polygon',
          style: dragBoxStyle,
        });
        scope.dragBox.set('gctype', 'kis');
        scope.dragBox.set('interaction', 'Select');
        scope.dragBox.set('widget', 'mbtiles');

        scope.dragBox.on('boxend', function() {
          var extent = scope.dragBox.getGeometry().getExtent();
          var extentproj = ol.proj.transformExtent(
            extent,
            scope.map
              .getView()
              .getProjection()
              .getCode(),
            scope.mbtiles.srid
          );
          setExtent(extentproj);
          scope.dragBox.setActive(false);
          scope.map.removeInteraction(scope.dragBox);
          scope.addedddragbox = false;
          scope.mbtiles.fromCurrentSelection = false;
        });

        scope.dragBox.setActive(false);
        scope.addedddragbox = false;
        scope.selectArea = function() {
          if (!scope.addedddragbox) {
            scope.dragBox.setActive(true);
            gcInteractions.setCurrentToolBar(scope.toolBarWidget);
            scope.map.addInteraction(scope.dragBox);
            scope.addedddragbox = true;
          } else {
            scope.dragBox.setActive(false);
            scope.map.removeInteraction(scope.dragBox);
            scope.addedddragbox = false;
          }
        };

        var sourceFeature = new ol.source.Vector({
          //create empty vector
        });

        scope.SelectionLayer = new ol.layer.Vector({
          source: sourceFeature,
          style: gcStyleFactory.getStyle('select'),
        });
        scope.map.getLayers().insertAt(17, scope.SelectionLayer);
        scope.SelectionLayer.setVisible(false);

        scope.selectionCourante = function() {
          try {
            gaDomUtils.showGlobalLoader();
            scope.mbtiles.fromCurrentSelection = true;
            var featureCollection = SelectManager.getfeatures();
            var ftisnames = scope.mbtiles.ftis.map(function(x) {
              x.selected = false;
              return x.name;
            });
            featureCollection.features.map(function(x) {
              var ind = ftisnames.indexOf(x.id.split('.')[0]);
              if (ind !== -1) scope.mbtiles.ftis[ind].selected = true;
            });
            var extent = SelectManager.getExtent();
            var extentproj = ol.proj.transformExtent(
              extent,
              scope.map
                .getView()
                .getProjection()
                .getCode(),
              scope.mbtiles.srid
            );
            setExtent(extentproj);
            scope.dragBox.setActive(false);
            scope.addedddragbox = false;
            scope.mbtiles.applyFilter = true;
            gaDomUtils.hideGlobalLoader();
          } catch (e) {
            gaDomUtils.hideGlobalLoader();
            scope.mbtiles.fromCurrentSelection = false;
            require('toastr').error(
              $filter('translate')('itv.correspondance.nofeatureselected')
            );
          }
        };

        scope.selectionPersonalise = function() {
          scope.mbtiles.fromCurrentSelection = false;
        };
        var TYPE = 'mbtiles';
        function getResponseFile(d) {
          switch (d.etat) {
            case 'FINISHED':
              scope.refreshList();
              scope.getFile(d);
              break;
            case 'FAILED':
              require('toastr').error(d.reason);
              break;
          }
        }

        var getMbtilesParametersg2c = function(mbtiles, geoserverMbtiles) {
          var LAYERS = gclayers
            .getOperationalLayerg2c()
            .map(function(x) {
              if (x.fti && x.fti.name) return x.fti.name;
            })
            .filter(function(x) {
              if (x) return x;
            });

          var mbtilesnames = [];
          var layersuids = [];
          var mbtileslayers = mbtiles.ftis
            .map(function(x) {
              if (x.selected && x.type === 'g2c') {
                mbtilesnames.push(x.name);
                layersuids.push(x.uid);
                return x;
              }
            })
            .filter(function(x) {
              if (x) return x;
            });
          var layers = [],
            styles = [],
            opacity = [],
            cql_filter = [],
            gcqlfilter = '';
          if (geoserverMbtiles) {
            var ll = [],
              ss = [],
              oo = [],
              cc = [],
              gg = '';
            for (var i = 0; i < mbtilesnames.length; i++) {
              var ind = LAYERS.indexOf(mbtilesnames[i]);
              if (ind !== -1) {
                var x = mbtileslayers[i];
                ll.push(x.name);

                if (x.style) ss.push(x.style);
                else ss.push('');

                if (x.opacity) oo.push(x.opacity);
                else oo.push('1');

                if (x.cql_filter) {
                  cc.push(x.cql_filter);
                } else {
                  cc.push('1=1');
                }
              }
            }
            layers.push(ll.join(','));
            styles.push(ss.join(','));
            opacity.push(oo.join(','));
            cql_filter.push(cc.join(';'));
          } else {
            var j = angular.isDefined(mbtiles.minzoom) ? mbtiles.minzoom : 0;
            var maxzoom = angular.isDefined(mbtiles.maxzoom)
              ? mbtiles.maxzoom
              : 15;
            while (j <= maxzoom) {
              var resolution = zoom_levels[j];
              var ll = [],
                ss = [],
                oo = [],
                cc = [],
                gg = '';
              for (var i = 0; i < mbtilesnames.length; i++) {
                var ind = LAYERS.indexOf(mbtilesnames[i]);
                if (ind !== -1) {
                  var gccatalogue = gclayers.getOperationalLayerg2c()[ind];
                  var minResolution = gccatalogue.getMinResolution();
                  var maxResolution = gccatalogue.getMaxResolution();
                  if (
                    angular.isUndefined(resolution) ||
                    (resolution <= maxResolution && resolution >= minResolution)
                  ) {
                    var x = mbtileslayers[i];
                    ll.push(x.name);

                    if (x.style) ss.push(x.style);
                    else ss.push('');

                    if (x.opacity) oo.push(x.opacity);
                    else oo.push('1');

                    if (x.cql_filter) {
                      cc.push(x.cql_filter);
                    } else {
                      cc.push('1=1');
                    }
                  }
                }
              }
              layers.push(ll.join(','));
              styles.push(ss.join(','));
              opacity.push(oo.join(','));
              cql_filter.push(cc.join(';'));
              j++;
            }
          }

          var sendata = {
            layers: layers,
            styles: styles,
            opacity: opacity,
            cql_filter: cql_filter,
            gcqlfilter: gcqlfilter,
            layersuids: layersuids.join(','),
            type: 'g2c',
          };
          return sendata;
        };

        var getMbtilesParametersEsri = function(mbtiles) {
          var esriLayers = [];
          var urlsesri = [];
          var wfssesri = [];
          var LAYERS = gclayers
            .getOperationalLayerESRI()
            .map(function(x) {
              if (x.fti && x.fti.name) {
                if (urlsesri.indexOf(x.fti.wms) === -1) {
                  urlsesri.push(x.fti.wms);
                  wfssesri.push(x.fti.wfs);
                }
                return x.fti.name;
              }
            })
            .filter(function(x) {
              if (x) return x;
            });

          for (var index = 0; index < urlsesri.length; index++) {
            var mbtilesnames = [];
            var layersuids = [];
            var mbtileslayers = mbtiles.ftis
              .map(function(x) {
                if (
                  x.selected &&
                  x.type === 'esri' &&
                  x.wms === urlsesri[index]
                ) {
                  mbtilesnames.push(x.name);
                  layersuids.push(x.uid);
                  return x;
                }
              })
              .filter(function(x) {
                if (x) return x;
              });

            var layers = [],
              styles = [],
              opacity = [],
              cql_filter = [],
              gcqlfilter = '';
            var j = angular.isDefined(mbtiles.minzoom) ? mbtiles.minzoom : 0;
            var maxzoom = angular.isDefined(mbtiles.maxzoom)
              ? mbtiles.maxzoom
              : 15;
            while (j <= maxzoom) {
              var resolution = zoom_levels[j];
              var ll = [],
                ss = [],
                oo = [],
                cc = [],
                gg = '';
              for (var i = 0; i < mbtilesnames.length; i++) {
                var ind = LAYERS.indexOf(mbtilesnames[i]);
                if (ind !== -1) {
                  var gccatalogue = gclayers.getOperationalLayerESRI()[ind];
                  var minResolution = gccatalogue.getMinResolution();
                  var maxResolution = gccatalogue.getMaxResolution();
                  if (
                    angular.isUndefined(resolution) ||
                    (resolution <= maxResolution && resolution >= minResolution)
                  ) {
                    var x = mbtileslayers[i];
                    ll.push(x.name);

                    if (x.style) ss.push(x.style);
                    else ss.push('');

                    if (x.opacity) oo.push(x.opacity);
                    else oo.push('1');

                    if (x.cql_filter) {
                      cc.push(x.cql_filter);
                    } else {
                      cc.push('1=1');
                    }
                  }
                }
              }
              layers.push(ll.join(','));
              styles.push(ss.join(','));
              opacity.push(oo.join(','));
              cql_filter.push(cc.join(';'));
              j++;
            }

            var sendata = {
              layers: layers,
              styles: styles,
              opacity: opacity,
              cql_filter: cql_filter,
              layersuids: layersuids.join(','),
              type: 'esri',
              wms: urlsesri[index],
              wfs: wfssesri[index],
            };
            esriLayers.push(sendata);
          }
          return esriLayers;
        };

        scope.exportMBTILES = function(mbtiles) {
          scope.mbtiles.filename = scope.mbtiles.filename.trim();

          if (
            !(
              scope.mbtiles.bbox.maxx > scope.mbtiles.bbox.minx &&
              scope.mbtiles.bbox.maxy > scope.mbtiles.bbox.miny
            )
          ) {
            require('toastr').error(
              $filter('translate')('importExportMBTILES.messages.badbbox')
            );
            return;
          }

          var ext = [
            mbtiles.bbox.minx,
            mbtiles.bbox.miny,
            mbtiles.bbox.maxx,
            mbtiles.bbox.maxy,
          ];
          var extentproj3857 = ol.proj.transformExtent(
            ext,
            mbtiles.srid,
            'EPSG:3857'
          );
          var extentproBuffer = [
            extentproj3857[0] - 1,
            extentproj3857[1] + 1,
            extentproj3857[2] + 1,
            extentproj3857[3] - 1,
          ];
          var extentproj = ol.proj.transformExtent(
            extentproBuffer,
            'EPSG:3857',
            mbtiles.srid
          );
          var sendata = {
            format: mbtiles.format,
            version: mbtiles.version,
            minzoom: angular.isDefined(mbtiles.minzoom) ? mbtiles.minzoom : 0,
            maxzoom: angular.isDefined(mbtiles.maxzoom) ? mbtiles.maxzoom : 15,
            bbox:
              extentproj[0] +
              ',' +
              extentproj[1] +
              ',' +
              extentproj[2] +
              ',' +
              extentproj[3],
            crs: mbtiles.srid,
            filename: mbtiles.filename,
            transparent:
              mbtiles.transparent === $filter('translate')('common.yes')
                ? true
                : false,
            openstreetmap: mbtiles.openstreetmap,
            zoom: mbtiles.zoominit,
            geoserverMbtiles: mbtiles.mbtilesGeoserver,
          };

          var sendatag2c = getMbtilesParametersg2c(
            mbtiles,
            mbtiles.mbtilesGeoserver
          );
          var sendataesri = getMbtilesParametersEsri(mbtiles);
          sendata.g2c = sendatag2c;
          sendata.esri = sendataesri;
          var layersuids = [];
          if (sendatag2c && sendatag2c.layersuids.replace(',', ''))
            layersuids = sendatag2c.layersuids.split(',');
          if (sendataesri) {
            for (var zz = 0; zz < sendataesri.length; zz++) {
              if (
                sendataesri[zz] &&
                sendataesri[zz].layersuids &&
                sendataesri[zz].layersuids.replace(',', '')
              )
                layersuids = layersuids.concat(
                  sendataesri[zz].layersuids.split(',')
                );
            }
          }
          sendata.layersuids = layersuids.join(',');

          if (scope.mbtiles.ftis.length > 0) {
            if (sendata.maxzoom > 18 || sendata.maxzoom > 18)
              require('toastr').info(
                $filter('translate')('importExportMBTILES.messages.time')
              );

            //if ( !scope.mbtiles.createboth )
            var promise = mbtilesService.exportMBTILES(sendata);
            /*else
                            promise = geopackageService.exportGeopackageMbtiles(sendata , TYPE);*/

            if (scope.mbtiles.runonbackground) {
              gaDomUtils.showPreciseLocalLoader('.' + scope.widgetName);
              promise.then(
                function(res) {
                  if (res.data.etat === 'RUNNING') {
                    // if ( res.data.creation )
                    //     res.data.creation = $filter('date')(new Date(res.data.creation) , 'dd MMM yyyy HH:mm');
                    if (res.data.type && res.data.type.indexOf('/') !== -1)
                      res.data.both = true;
                    else res.data.both = false;
                    scope.currentProcess.push(res.data);
                    scope.tableParamsProcessus.reload();
                    require('toastr').info(
                      $filter('translate')(
                        'importExportMBTILES.runningonbackground'
                      )
                    );
                    gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                    $rootScope.$broadcast('newProcessCreated', 0);
                  } else if (
                    res.data.etat === 'FINISHED' &&
                    res.data.progress === 100
                  ) {
                    gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                    require('toastr').info(
                      $filter('translate')(
                        'importExportMBTILES.runningonbackground'
                      )
                    );
                    $rootScope.$broadcast('newProcessCreated', 0);
                  } else if (res.data.etat === 'FAILED') {
                    gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                    require('toastr').error(
                      $filter('translate')(
                        'importExportMBTILES.messages.nombtiles'
                      )
                    );
                    $rootScope.$broadcast('newProcessCreated', 0);
                  }
                },
                function(res) {
                  require('toastr').error(res.data.message);
                  gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                }
              );
            } else {
              gaDomUtils.showPreciseLocalLoader('.' + scope.widgetName);
              promise.then(
                function(res) {
                  if (res.data.etat === 'RUNNING') {
                    // if ( res.data.creation )
                    //     res.data.creation = $filter('date')(new Date(res.data.creation) , 'dd MMM yyyy HH:mm');
                    scope.currentProcess.push(res.data);
                    scope.tableParamsProcessus.reload();
                    var stop = $interval(function() {
                      // if ( res.data.creation )
                      //     res.data.creation = new Date(res.data.creation).getTime();
                      // if ( res.data.end )
                      //     res.data.end = new Date(res.data.end).getTime();
                      delete res.data.both;
                      mbtilesService.getProgression(res.data).then(
                        function(res) {
                          if (
                            res.data.etat === 'FINISHED' &&
                            res.data.progress === 100
                          ) {
                            $interval.cancel(stop);
                            getResponseFile(res.data);
                            gaDomUtils.removeLocalLoader(
                              '.' + scope.widgetName
                            );
                            // $rootScope.$broadcast('newProcessCreated' , 0);
                          } else if (res.data.etat === 'FAILED') {
                            $interval.cancel(stop);
                            gaDomUtils.removeLocalLoader(
                              '.' + scope.widgetName
                            );
                            require('toastr').error(
                              $filter('translate')(
                                'importExportMBTILES.messages.nombtiles'
                              )
                            );
                            // $rootScope.$broadcast('newProcessCreated' , 0);
                          }
                        },
                        function() {
                          gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                          $interval.cancel(stop);
                          require('toastr').error(
                            $filter('translate')(
                              'importExportMBTILES.messages.nombtiles'
                            )
                          );
                        }
                      );
                    }, 10000);
                  } else {
                    require('toastr').error(res.data.reason);
                    gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                  }
                },
                function(res) {
                  require('toastr').error(res.data.message);
                  gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                }
              );
            }
          } else {
            require('toastr').error(
              $filter('translate')('importExportMBTILES.messages.noftis')
            );
          }
        };

        processFactory.getProcessByUsertype(TYPE).then(function(res) {
          scope.currentProcess = res.data;
          scope.tableParamsProcessus = new ngTableParams(
            {
              page: 1, // show first page
              count: 5, // count per page
            },
            {
              total: 0, // length of data
              counts: [5, 10, 15],
              getData: function($defer, params) {
                var displayedTab = scope.currentProcess.slice(
                  (params.page() - 1) * params.count(),
                  params.page() * params.count()
                );

                params.total(scope.currentProcess.length); // set total for recalc pagination

                if (
                  params.page() != 1 &&
                  scope.currentProcess.length == params.count()
                ) {
                  params.page(params.page() - 1);
                }
                $defer.resolve(displayedTab);
              },
            }
          );
        });

        scope.refreshList = function() {
          gaDomUtils.showGlobalLoader();
          processFactory.getProcessByUsertype(TYPE).then(
            function(res) {
              scope.currentProcess = res.data;
              scope.tableParamsProcessus.reload();
              gaDomUtils.hideGlobalLoader();
            },
            function() {
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        scope.getQrCode = function(rapport) {
          var mobhost =
            $location.protocol() +
            '://' +
            $location.host() +
            ':' +
            $location.port();
          var appname = localStorage.getItem('app');
          if ($location.search().app) {
            appname = $location.search().app;
          }
          scope.mobqrcode =
            '/services/' +
            $rootScope.xgos.portal.uid +
            '/process/qrcode?name=' +
            appname +
            '&token=' +
            gaUrlUtils.encodeUriQuery(localStorage.getItem('auth_token')) +
            '&url=' +
            mobhost +
            '&uid=' +
            rapport.uid;
          scope.titleqrcode =
            $filter('translate')('process.process.qrmbtiles') +
            ' ' +
            rapport.file;
          ngDialog.open({
            template: 'js/XG/widgets/mapapp/main/views/barecode.html',
            className: 'ngdialog-theme-plain width300 miniclose',
            closeByDocument: false,
            scope: scope,
          });
        };

        scope.deleteProcess = function(rapport) {
          swal(
            {
              title: $filter('translate')('importExportMBTILES.sure'),
              //text: "You will not be able to recover this imaginary file!",
              type: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#DD6B55',
              confirmButtonText: $filter('translate')('common.yes'),
              cancelButtonText: $filter('translate')('common.no'),
              closeOnConfirm: false,
            },
            function(isConfirm) {
              if (isConfirm) {
                processFactory.deleteProcess(rapport).then(
                  function(res) {
                    var index;
                    for (var i = 0; i < scope.currentProcess.length; i++) {
                      if (scope.currentProcess[i].uid === rapport.uid) {
                        index = i;
                        break;
                      }
                    }
                    scope.currentProcess.splice(index, 1);
                    scope.tableParamsProcessus.reload();
                    swal({
                      title: $filter('translate')(
                        'importExportMBTILES.deleted'
                      ),
                      text: $filter('translate')(
                        'importExportMBTILES.pdeleted'
                      ),
                      type: 'success',
                      showCancelButton: false,
                      showConfirmButton: false,
                      timer: 1000,
                    });
                  },
                  function() {
                    require('toastr').error(
                      $filter('translate')('process.process.processnotavailabe')
                    );
                  }
                );
              }
            }
          );
        };

        scope.zooms = [];
        for (var i = 0; i <= 19; i++) {
          scope.zooms.push(i);
        }

        scope.visibleonmap = false;
        scope.changedVisibility = function() {
          scope.SelectionLayer.setVisible(scope.visibleonmap);
        };
        scope.getFile = function(rapport) {
          if (rapport.type.split('/').length === 1)
            window.open(
              '/services/' +
                $rootScope.xgos.portal.uid +
                '/mbtiles/getFile?f=json&uid=' +
                rapport.uid +
                '&etat=' +
                rapport.etat +
                '&file=' +
                rapport.file +
                '&type=' +
                rapport.type +
                '&token=' +
                encodeURIComponent(localStorage.getItem('auth_token'))
            );
          else {
            window.open(
              '/services/' +
                $rootScope.xgos.portal.uid +
                '/geopackage/getZipFile?f=json&uid=' +
                rapport.uid +
                '&etat=' +
                rapport.etat +
                '&file=' +
                rapport.file +
                '&type=mbtiles&token=' +
                encodeURIComponent(localStorage.getItem('auth_token'))
            );
          }
        };

        scope.$on('openTools_imexmbtiles', function(event, arg) {
          scope.getMapExtent();
          scope.SelectionLayer.setVisible(scope.visibleonmap);
        });

        scope.$on('openCloseTools_imexmbtiles', function(event, arg) {
          if (arg.active) {
            scope.SelectionLayer.setVisible(scope.visibleonmap);
          } else {
            scope.SelectionLayer.setVisible(false);
          }
        });

        scope.$on('closeTools_imexmbtiles', function(event, arg) {
          scope.SelectionLayer.setVisible(false);
          scope.dragBox.setActive(false);
          scope.addedddragbox = false;
          scope.map.removeInteraction(scope.dragBox);
        });
      },
    };
  };

  imexMbtiles.$inject = [
    'mbtilesService',
    'FeatureTypeFactory',
    '$filter',
    'gcStyleFactory',
    'gaDomUtils',
    'SelectManager',
    '$interval',
    '$rootScope',
    'gcInteractions',
    'SridFactory',
    'processFactory',
    '$location',
    'ngDialog',
    'gaUrlUtils',
    'ngTableParams',
    'gclayers',
    '$timeout' /*, "geopackageService" */,
  ];
  return imexMbtiles;
});
