'use strict';
define(function() {
  /*
   * Params :
   * map /
   */
  var imexGeopackage = function(
    geopackageService,
    FeatureTypeFactory,
    $filter,
    gcStyleFactory,
    gaDomUtils,
    SelectManager,
    $interval,
    $rootScope,
    gcInteractions,
    SridFactory,
    processFactory,
    $location,
    ngDialog,
    gaUrlUtils,
    ngTableParams,
    gclayers,
    $timeout,
    extendedNgDialog,
    EditFactory,
    QueryFactory,
    gcPopup,
    gaJsUtils,
    mapJsUtils
  ) {
    return {
      // TODO verif model
      templateUrl:
        'js/XG/widgets/mapapp/exportgeopackage/views/exportGeopackage.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')('exportGeopackage.export'),
          },
          {
            title: $filter('translate')('exportGeopackage.process'),
          },
          {
            title: $filter('translate')('exportGeopackage.synchro'),
          },
        ];

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

        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.geopackage.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.geopackage.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.geopackage.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 stopgeo = $interval(function() {
          if (
            FeatureTypeFactory.resources.featuretypes &&
            FeatureTypeFactory.resources.featuretypes.length > 0
          ) {
            if (
              gclayers.getOperationalLayerg2c() &&
              gclayers.getOperationalLayerg2c().length > 0
            ) {
              scope.getFeatureFromCatalogue();
              $interval.cancel(stopgeo);
            }
          }
        }, 3000);

        scope.getFeatureFromCatalogue = function() {
          scope.geopackage.ftis = [];
          gclayers.getOperationalLayerg2c().map(function(x) {
            if (x.fti && x.fti.geographic && x.fti.name)
              scope.geopackage.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.geopackage.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.geopackage.ftis.map(function(x) {
            x.selected = false;
          });
        };

        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.geopackage.srid
          );
          setExtent(extentproj);
          scope.geopackage.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', 'geopackage');

        scope.dragBox.on('boxend', function() {
          var extent = scope.dragBox.getGeometry().getExtent();
          var extentproj = ol.proj.transformExtent(
            extent,
            scope.map
              .getView()
              .getProjection()
              .getCode(),
            scope.geopackage.srid
          );
          setExtent(extentproj);
          scope.dragBox.setActive(false);
          scope.map.removeInteraction(scope.dragBox);
          scope.addedddragbox = false;
          scope.geopackage.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(16, scope.SelectionLayer);
        scope.SelectionLayer.setVisible(false);

        scope.selectionCourante = function() {
          try {
            gaDomUtils.showGlobalLoader();
            scope.geopackage.fromCurrentSelection = true;
            var featureCollection = SelectManager.getfeatures();
            var ftisnames = scope.geopackage.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.geopackage.ftis[ind].selected = true;
            });
            var extent = SelectManager.getExtent();
            var extentproj = ol.proj.transformExtent(
              extent,
              scope.map
                .getView()
                .getProjection()
                .getCode(),
              scope.geopackage.srid
            );
            setExtent(extentproj);
            scope.dragBox.setActive(false);
            scope.addedddragbox = false;
            scope.geopackage.applyFilter = true;
            scope.geopackage.featureCollection = featureCollection;
            gaDomUtils.hideGlobalLoader();
          } catch (e) {
            gaDomUtils.hideGlobalLoader();
            scope.geopackage.fromCurrentSelection = false;
            require('toastr').error(
              $filter('translate')('itv.correspondance.nofeatureselected')
            );
          }
        };

        scope.selectionPersonalise = function() {
          scope.geopackage.fromCurrentSelection = false;
        };

        function getResponseFile(d) {
          switch (d.etat) {
            case 'FINISHED':
              scope.refreshList(true);
              scope.getFile(d);
              break;
            case 'FAILED':
              require('toastr').error(d.reason);
              break;
          }
        }

        var TYPE = 'gpkg';

        var getMbtilesParametersg2c = function(mbtiles) {
          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 = '';
          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.isnotmbtiles = true;
        scope.exportGeopackage = function(geopackage) {
          scope.geopackage.filename = scope.geopackage.filename.trim();
          if (
            !(
              scope.geopackage.bbox.maxx > scope.geopackage.bbox.minx &&
              scope.geopackage.bbox.maxy > scope.geopackage.bbox.miny
            )
          ) {
            require('toastr').error(
              $filter('translate')('exportGeopackage.messages.badbbox')
            );
            return;
          }

          if (
            !scope.geopackage.createboth &&
            (!scope.geopackage.mbtiles || !scope.geopackage.mbtiles.uid)
          ) {
            require('toastr').error(
              $filter('translate')('exportGeopackage.messages.choosembtiles')
            );
            return;
          }
          if (scope.geopackage.ismbtiles) {
            scope.isnotmbtiles = false;
          } else {
            scope.isnotmbtiles = true;
          }
          if (scope.isnotmbtiles) {
            var layers = [];
            geopackage.ftis
              .map(function(x) {
                if (x.selected) {
                  layers.push(x.uid);
                  return x;
                }
              })
              .filter(function(x) {
                if (x) return x;
              });

            var ext = [
              geopackage.bbox.minx,
              geopackage.bbox.miny,
              geopackage.bbox.maxx,
              geopackage.bbox.maxy,
            ];
            var extentproj3857 = ol.proj.transformExtent(
              ext,
              geopackage.srid,
              'EPSG:3857'
            );
            var extentproBuffer = [
              extentproj3857[0],
              extentproj3857[1],
              extentproj3857[2],
              extentproj3857[3],
            ];
            var extentproj = ol.proj.transformExtent(
              extentproBuffer,
              'EPSG:3857',
              geopackage.srid
            );

            /* var sendata = {
                            "layers": layers.join(","),
                            "bbox": extentproj[0] + "," + extentproj[1] + "," + extentproj[2] + "," + extentproj[3],
                            "crs": geopackage.srid,
                            "filename": geopackage.filename
                        };*/
            var sendata = {
              format: geopackage.format,
              version: geopackage.version,
              minzoom: angular.isDefined(geopackage.minzoom)
                ? geopackage.minzoom
                : 0,
              maxzoom: angular.isDefined(geopackage.maxzoom)
                ? geopackage.maxzoom
                : 15,
              bbox:
                extentproj[0] +
                ',' +
                extentproj[1] +
                ',' +
                extentproj[2] +
                ',' +
                extentproj[3],
              crs: geopackage.srid,
              filename: geopackage.filename,
              transparent:
                geopackage.transparent === $filter('translate')('common.yes')
                  ? true
                  : false,
              zoom: geopackage.zoominit,
              openstreetmap: geopackage.openstreetmap,
              createboth: geopackage.createboth,
              mbtiles: geopackage.mbtiles,
              layersuids: layers.join(','),
              isnotmbtiles: scope.isnotmbtiles,
            };
          } else {
            var ext = [
              geopackage.bbox.minx,
              geopackage.bbox.miny,
              geopackage.bbox.maxx,
              geopackage.bbox.maxy,
            ];
            var extentproj3857 = ol.proj.transformExtent(
              ext,
              geopackage.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',
              geopackage.srid
            );
            var sendata = {
              format: geopackage.format,
              version: geopackage.version,
              minzoom: angular.isDefined(geopackage.minzoom)
                ? geopackage.minzoom
                : 0,
              maxzoom: angular.isDefined(geopackage.maxzoom)
                ? geopackage.maxzoom
                : 15,
              bbox:
                extentproj[0] +
                ',' +
                extentproj[1] +
                ',' +
                extentproj[2] +
                ',' +
                extentproj[3],
              crs: geopackage.srid,
              filename: geopackage.filename,
              transparent:
                geopackage.transparent === $filter('translate')('common.yes')
                  ? true
                  : false,
              zoom: geopackage.zoominit,
              openstreetmap: geopackage.openstreetmap,
              createboth: geopackage.createboth,
              mbtiles: geopackage.mbtiles,
              isnotmbtiles: false,
            };

            var sendatag2c = getMbtilesParametersg2c(geopackage);
            var sendataesri = getMbtilesParametersEsri(geopackage);
            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(',');
          }
          var idfeatselected = [];
          if (scope.geopackage.featureCollection) {
            var featsSelected = scope.geopackage.featureCollection.features;
            for (var i = 0; i < featsSelected.length; i++) {
              idfeatselected.push(featsSelected[i].id);
            }
            //sendata.collection = scope.geopackage.featureCollection;
          }
          sendata.featselected = idfeatselected;
          if (geopackage.fromCurrentSelection == false) {
            sendata.featselected = [];
          }
          //var promise;
          /*if (!scope.geopackage.createboth)
                        promise = geopackageService.exportGeopackage(sendata);
                    else*/
          var promise = geopackageService.exportGeopackageMbtiles(
            sendata,
            TYPE
          );

          if (scope.geopackage.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.indexOf('/') !== -1) res.data.both = true;
                  else res.data.both = false;
                  scope.currentProcess.push(res.data);
                  scope.tableParamsProcessus.reload();
                  require('toastr').info(
                    $filter('translate')('exportGeopackage.runningonbackground')
                  );
                  gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                  $rootScope.$broadcast('newProcessCreated', 1);
                } else if (
                  res.data.etat === 'FINISHED' &&
                  res.data.progress === 100
                ) {
                  gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                  require('toastr').info(
                    $filter('translate')('exportGeopackage.runningonbackground')
                  );
                  $rootScope.$broadcast('newProcessCreated', 1);
                } else if (res.data.etat === 'FAILED') {
                  gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                  require('toastr').error(
                    $filter('translate')(
                      'exportGeopackage.messages.nogeopackage'
                    )
                  );
                  $rootScope.$broadcast('newProcessCreated', 1);
                }
              },
              function(res) {
                require('toastr').error(
                  'exportGeopackage.messages.nogeopackage'
                );
                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');
                  if (res.data.type.indexOf('/') !== -1) res.data.both = true;
                  else res.data.both = false;
                  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;
                    geopackageService.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' , 1);
                        } else if (res.data.etat === 'FAILED') {
                          $interval.cancel(stop);
                          gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                          require('toastr').error(
                            $filter('translate')(
                              'exportGeopackage.messages.nogeopackage'
                            )
                          );
                          // $rootScope.$broadcast('newProcessCreated' , 1);
                        }
                      },
                      function() {
                        gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                        $interval.cancel(stop);
                        require('toastr').error(
                          $filter('translate')(
                            'exportGeopackage.messages.nogeopackage'
                          )
                        );
                      }
                    );
                  }, 10000);
                } else {
                  require('toastr').error(res.data.reason);
                  gaDomUtils.removeLocalLoader('.' + scope.widgetName);
                }
              },
              function(res) {
                require('toastr').error(res.data.message);
                gaDomUtils.removeLocalLoader('.' + scope.widgetName);
              }
            );
          }
        };

        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.currentProcessSynchro = [{}];

        scope.tableParamsProcessusSynchro = 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.currentProcessSynchro.slice(
                (params.page() - 1) * params.count(),
                params.page() * params.count()
              );

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

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

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

        var stop;
        scope.changedRefresh = function() {
          if (scope.geopackage.automaticrefresh)
            stop = $interval(function() {
              scope.refreshList(false);
            }, 30000);
          else {
            if (stop) $interval.cancel(stop);
          }
        };
        scope.changedRefresh();

        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.geopackage.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')('exportGeopackage.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')('exportGeopackage.deleted'),
                      text: $filter('translate')('exportGeopackage.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.getZoomFromMap = function(type) {
          switch (type) {
            case 'init':
              scope.geopackage.zoominit = scope.map.getView().getZoom();
              break;
            default:
              scope.geopackage.maxzoom = scope.map.getView().getZoom();
              break;
          }
        };

        scope.getFile = function(rapport) {
          if (rapport.type.split('/').length === 1)
            window.open(
              '/services/' +
                $rootScope.xgos.portal.uid +
                '/geopackage/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.$watch('geopackage.selectedFile', function(newValue, oldValue) {
          if (newValue !== oldValue) {
            console.log(newValue);
          }
        });
        //
        scope.mapCode = scope.map
          .getView()
          .getProjection()
          .getCode();
        scope.components = [];
        scope.getTabledForFile = function(selectedFile) {
          //console.log(scope.currentProcess)
          //console.log(scope.geopackage.selectedFile);
          if (scope.components.length != 0) {
            scope.components = [];
          }
          // geopackageService.getTablesGeopackage(scope.geopackage.selectedFile.uid).then(function(res){
          geopackageService
            .getTablesGeopackage(selectedFile.uid)
            .then(function(res) {
              console.log(res.data);
              if (res.data.length != 0) {
                for (var i = 0; i < res.data.length; i++) {
                  var component_name = res.data[i].replace('_geopackage', '');
                  // if (rapport.synchronised == true)
                  scope.components.push(component_name);
                }
              }
            });
        };
        scope.testComponent = function() {
          scope.lisComponent = false;
          //console.log(scope.geopackage.componentSelected);
        };
        scope.synchroGeopackage = function() {
          scope.lisComponent = true;
          scope.uidComponent = FeatureTypeFactory.getFeatureUidByName(
            scope.geopackage.componentSelected
          );
          scope.componentFti = FeatureTypeFactory.getFeatureByUid(
            scope.uidComponent
          );
          scope.whereClause = '1=1';
          scope.buttonactions = [
            {
              label: 'btn',
              btnclass: 'default',
              cfg: {
                iconOrLabel: 'label',
                label: 'synchronise',
                size: 'btn-xs',
              },
              config: { click: ['synchronise'] },
            },
          ];

          //console.log(scope.componentFti);
        };
        scope.closepanel = function() {
          scope.panelsManager.removePanel('objstoadd');
          scope.panelsManager.removePanel('geopackage');

          scope.clearGeom();
        };
        scope.verifyObjForSynhcro = function(id, tab) {
          for (var k = 0; k < tab.length; k++) {
            if (id == tab[k]) {
              return true;
            }
          }
          return false;
        };
        scope.MAJAttribut = function(att) {
          if (att.type == 'java.sql.Timestamp') {
            //scope.selectedObject.properties[att.name]= scope.KCProps[att.name]+"T00:00:00.000+0000" ;
            scope.selectedObject.properties[att.name] = scope.KCProps[att.name];
          } else {
            scope.selectedObject.properties[att.name] = scope.KCProps[att.name];
          }
        };
        scope.MAJAllAttributs = function() {
          swal(
            {
              title:
                'Etes vous sure de vouloir mettre à jour tous les attributs ?',
              //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: true,
            },
            function(isConfirm) {
              if (isConfirm) {
                var tabAtt = scope.componentFti.attributes;
                for (var k = 0; k < tabAtt.length; k++) {
                  scope.MAJAttribut(tabAtt[k]);
                }
              }
            }
          );
        };

        scope.MAJGeom = function() {
          swal(
            {
              title: 'Etes vous sure de vouloir mettre à jour la géometrie ?',
              //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: true,
            },
            function(isConfirm) {
              if (isConfirm) {
                scope.selectedObject.geometry = scope.mobileObejct.geometry;
              }
            }
          );
        };

        scope.clearGeom = function() {
          gclayers
            .getDrawLayer()
            .getSource()
            .clear();
          gclayers.clearhighLightFeatures();
        };

        scope.drawAndLocGeom = function(obj) {
          scope.clearGeom();
          mapJsUtils.drawSelectedFeature(obj);
          mapJsUtils.localiseData(obj, scope.map);
        };

        scope.localiseGeom = function(obj) {
          mapJsUtils.localiseData(obj, scope.map);
        };

        /**
         * some features contain extra informations (ie dossier anc) and are not compliant geojson features
         * we may need to clean it before localisation for exemple
         * @param obj
         */

        //Mise en évidence sur la carte d'un objet
        scope.highLightFeature = function(obj) {
          var format = new ol.format.GeoJSON();
          var copy = gaJsUtils.getCleanFeature(obj);
          var f = format.readFeature(copy);
          gclayers.addhighLightFeature(f);
        };
        scope.removehighLightFeature = function(obj) {
          var format = new ol.format.GeoJSON();
          var copy = gaJsUtils.getCleanFeature(obj);
          var f = format.readFeature(copy);
          gclayers.removehighLightFeatures(f);
        };
        scope.compareGeoms = function(selectedObj, mobileObj) {
          if (mobileObj != undefined) {
            var format = new ol.format.GeoJSON();
            var f1 = format.readFeature(selectedObj);
            var f2 = format.readFeature(mobileObj);
            var E1 = f1.getGeometry().getExtent();
            var E2 = f2.getGeometry().getExtent();

            for (var k = 0; k < E1.length; k++) {
              if (E1[k].toFixed(0) != E2[k].toFixed(0)) {
                return false;
                break;
              }
            }
            return true;
          }
        };
        scope.compareAttributs = function(att, selectedObj, mobileObj) {
          //console.log(selectedObj.properties,mobileObj.properties)
          if (
            selectedObj.properties[att.name] == mobileObj.properties[att.name]
          ) {
            return true;
          } else if (
            selectedObj.properties[att.name] == null &&
            mobileObj.properties[att.name] == 0
          ) {
            return true;
          } else if (
            selectedObj.properties[att.name] == null &&
            mobileObj.properties[att.name] == 'false'
          ) {
            return true;
          } else if (
            selectedObj.properties[att.name] == false &&
            mobileObj.properties[att.name] == 'false'
          ) {
            return true;
          } else if (
            selectedObj.properties[att.name] == true &&
            mobileObj.properties[att.name] == 'true'
          ) {
            return true;
          } else if (
            selectedObj.properties[att.name] == '' &&
            mobileObj.properties[att.name] == null
          ) {
            return true;
          } else if (
            att.type == 'java.util.Date' ||
            att.type == 'java.sql.Timestamp' ||
            att.type == 'java.sql.Time' ||
            att.type == 'java.sql.Date'
          ) {
            var dateC = selectedObj.properties[att.name];
            dateC = $filter('date')(dateC, 'yyyy-MM-dd');
            if (dateC == mobileObj.properties[att.name]) {
              return true;
            }
          } else if (att.type == 'java.lang.String') {
            var str = selectedObj.properties[att.name];
            if (str != null) {
              str = selectedObj.properties[att.name].trim();
              if (str == mobileObj.properties[att.name]) {
                return true;
              } else if (str == '' && mobileObj.properties[att.name] == null) {
                return true;
              }
            }
          } else {
            return false;
          }
        };
        /***************SYNCHRONISATION*********************/
        /**
         * [compareTheTwoObjects verifie si les deux objets (postgres et mobile) sont egaux ]
         * @param  {[type]} selectedObj [description]
         * @param  {[type]} mobileObj   [description]
         * @return {[type]}             [description]
         */
        scope.compareTheTwoObjects = function(selectedObj, mobileObj) {
          var tabAtt = scope.componentFti.attributes;
          for (var k = 0; k < tabAtt.length; k++) {
            if (!scope.compareAttributs(tabAtt[k], selectedObj, mobileObj)) {
              return false;
              break;
            }
          }
          return true;
        };

        var dialog;
        /**
         * [compareAndSynchornise ouvre une interface de comparaison]
         * @param  {[type]} obj [description]
         * @return {[type]}     [description]
         */
        scope.compareAndSynchornise = function(obj) {
          scope.selectedObject = obj;
          scope.forceHeight = '250px';
          scope.height = '250px';
          var projection = scope.map.getView().getProjection();
          scope.mapCode = projection.getCode();
          var testCoords = ol.proj.transform(
            [
              scope.selectedObject.geometry.coordinates[0],
              scope.selectedObject.geometry.coordinates[1],
            ],
            scope.mapCode,
            'EPSG:4326'
          );
          scope.currProps = scope.selectedObject.properties;
          geopackageService
            .getModifiedObjectById(
              scope.geopackage.selectedFile.uid,
              obj.id,
              scope.mapCode
            )
            .then(function(res) {
              scope.mobileObejct = res.data.features[0];
              scope.KCProps = scope.mobileObejct.properties;
            });
          dialog = extendedNgDialog.open({
            template:
              'js/XG/widgets/mapapp/exportgeopackage/views/componentSynchronisation-copie.html',
            className:
              'ngdialog-theme-plain width600 height700 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
            title: 'Synchronisation  ' + obj.id,
            draggable: true,
            preCloseCallback: function() {
              scope.clearGeom();
            },
          });
        };

        scope.OpenDataTabale = function() {
          console.log(scope.geopackage.selectedFile);
          scope.actionsyn = true;
          scope.uidComponent = FeatureTypeFactory.getFeatureUidByName(
            scope.geopackage.componentSelected
          );
          scope.componentFti = FeatureTypeFactory.getFeatureByUid(
            scope.uidComponent
          );
          var dateCrea = scope.geopackage.selectedFile.creation;
          var converteDate = new Date(dateCrea).getTime();

          //A ajouter
          //1- recuperation des objets for UPDATE
          geopackageService
            .getObjectsForUpdate(scope.geopackage.selectedFile.uid)
            .then(function(resu) {
              scope.updatedObjsForSync = resu.data;
              var updatedObjs = [];
              for (var i = 0; i < resu.data.length; i++) {
                if (
                  !inArray(
                    resu.data[i],
                    scope.geopackage.selectedFile.synchonisedObjs
                  )
                ) {
                  updatedObjs.push(resu.data[i]);
                }
              }
              var objects = JSON.stringify(updatedObjs);
              if (objects) {
                objects = objects.substring(1, objects.length - 1);
                objects = objects.replace(/"/g, "'");
                scope.whereUpdate = 'id IN ' + '(' + objects + ')';
              }
            });
          //2- recuperation des objets for DELETE
          geopackageService
            .getObjectsForDelete(scope.geopackage.selectedFile.uid)
            .then(function(resd) {
              scope.deletedObjsForSync = resd.data;
              var objects = JSON.stringify(scope.deletedObjsForSync);
              if (objects) {
                objects = objects.substring(1, objects.length - 1);
                objects = objects.replace(/"/g, "'");
                scope.whereDelete = 'id IN ' + '(' + objects + ')';
              }
            });
          geopackageService
            .getObjectsForUpdateGeom(scope.geopackage.selectedFile.uid)
            .then(function(resug) {
              scope.updatedObjsGeoms = resug.data;
            });
          // récupération des objets pour ADD
          geopackageService
            .getObjectsForAdd(scope.geopackage.selectedFile.uid)
            .then(function(resadd) {
              scope.addedObjs = resadd.data;
            });

          //A FAIRE
          //verify if object in updated objs
          scope.verifyupdated = function(obj) {
            var tab = scope.updatedObjsForSync;
            //var tab2 = scope.updatedObjsGeoms;
            if (
              scope.verifyObjForSynhcro(obj.id, tab) &&
              !scope.verifyissynchro(obj)
            ) {
              return true;
            } else {
              return false;
            }
          };
          //verify if object in deleted objss
          scope.verifydeleted = function(obj) {
            var tab = scope.deletedObjsForSync;
            if (
              scope.verifyObjForSynhcro(obj.id, tab) &&
              !scope.verifyissynchro(obj)
            ) {
              return true;
            } else {
              return false;
            }
          };
          /// verify if object in added list objects
          scope.verifyadded = function(obj) {
            var tab = scope.geopackage.selectedFile.addedObjs;
            //var tab2 = scope.updatedObjsGeoms;
            if (inArray(obj.id, tab)) {
              return true;
            } else {
              return false;
            }
          };

          scope.verifyissynchro = function(obj) {
            var tab1 = [];
            var tab2 = [];
            if (
              scope.geopackage.selectedFile.updatedObjs == null ||
              scope.geopackage.selectedFile.synchonisedObjs == null
            ) {
              return false;
            } else {
              tab1 = scope.geopackage.selectedFile.updatedObjs;
              tab2 = scope.geopackage.selectedFile.synchonisedObjs;
              if (
                scope.verifyObjForSynhcro(obj.id, tab1) ||
                scope.verifyObjForSynhcro(obj.id, tab2)
              ) {
                return true;
              } else {
                return false;
              }
            }
          };
          geopackageService
            .getAllObjectsGeopackage(scope.geopackage.selectedFile.uid)
            .then(function(res1) {
              scope.AllObjs = res1.data;
              var tabA = scope.geopackage.selectedFile.addedObjs;
              var concTab;
              if (tabA != undefined && tabA.length > 1) {
                concTab = scope.AllObjs.concat(tabA);
                scope.AllObjs = concTab;
              }
              var objects = JSON.stringify(scope.AllObjs);
              if (objects) {
                objects = objects.substring(1, objects.length - 1);
                objects = objects.replace(/"/g, "'");
                scope.whereClause = 'id IN ' + '(' + objects + ')';
              }
              scope.where = scope.whereClause;
              scope.addwhere = function() {
                var tabA = scope.geopackage.selectedFile.addedObjs;
                var tabB = scope.geopackage.selectedFile.synchonisedObjs;

                var synchrTab;
                if (
                  tabA != undefined &&
                  tabA != null &&
                  tabB != undefined &&
                  tabB != null
                ) {
                  synchrTab = tabB.concat(tabA);
                }
                var objects = JSON.stringify(synchrTab);
                if (objects) {
                  objects = objects.substring(1, objects.length - 1);
                  objects = objects.replace(/"/g, "'");
                  scope.whereModifs = 'id IN ' + '(' + objects + ')';
                }
                scope.where = scope.whereModifs;
              };
              scope.addwheredelete = function() {
                scope.where = scope.whereDelete;
              };
              scope.addwhereupdate = function() {
                scope.where = scope.whereUpdate;
              };
              scope.resetwhere = function() {
                scope.panelsManager.removePanel('objstoadd');
                scope.closepanel();
                $rootScope.$broadcast('refreshDatatable', {
                  uid: scope.componentFti.uid,
                });
                scope.panelsManager.addPanel({
                  id: 'geopackage',
                  stickToRight: true,
                  templateUrl:
                    'js/XG/widgets/mapapp/exportgeopackage/views/popoverDataComponent.html',
                  scope: scope,
                  stickToBorder: true,
                  visible: true,
                  resizable: true,
                });
                //scope.OpenDataTabale();
                scope.where = scope.whereClause;
              };
              var dialogAddObjs;
              scope.addedObjsForComponent = [];
              /**
               * [addobjects opendatatable qui liste les objets à ajouter ]
               * @return {[type]} [description]
               */
              scope.addobjects = function() {
                console.log(scope.addedObjs, scope.uidComponent);
                for (var i = 0; i < scope.addedObjs.length; i++) {
                  if (scope.addedObjs[i].startsWith(scope.componentFti.name)) {
                    if (
                      !inArray(
                        scope.addedObjs[i],
                        scope.geopackage.selectedFile.addedSqliteObjs
                      ) &&
                      !inArray(scope.addedObjs[i], scope.addedObjsForComponent)
                    ) {
                      scope.addedObjsForComponent.push(scope.addedObjs[i]);
                    }
                  }
                }
                scope.tableResult = {
                  elements: {
                    features: [],
                  },
                };

                geopackageService
                  .getCollObjectByIds(
                    scope.geopackage.selectedFile.uid,
                    scope.addedObjs.toString(),
                    scope.componentFti.name,
                    scope.mapCode
                  )
                  .then(function(res) {
                    console.log(res.data.features);
                    scope.geoj = res.data;
                    if (scope.geopackage.selectedFile.addedSqliteObjs == null) {
                      scope.geopackage.selectedFile.addedSqliteObjs = [];
                    }
                    var features = [];
                    for (var k = 0; k < res.data.features.length; k++) {
                      if (
                        !inArray(
                          res.data.features[k].id,
                          scope.geopackage.selectedFile.addedSqliteObjs
                        )
                      ) {
                        features.push(res.data.features[k]);
                      }
                    }
                    scope.geoj.features = features;

                    //////////////Ajout des boutons ajout d'objet et localise des objets à ajouter
                    scope.actionsynadd = [
                      {
                        name: 'addforsynch',
                        icone: 'fa fa-location-arrow',
                        localise: function(obj) {
                          console.log(obj.id);
                          scope.visulaiserGeom(obj.id);
                        },
                      },
                      {
                        name: 'addforsynch',
                        icone: 'fa fa-plus',
                        add: function(obj) {
                          console.log(obj.id);
                          scope.ajouterObjettoBDD(obj.id);
                          var index = scope.geoj.features.indexOf(obj);
                          if (index > -1) {
                            scope.geoj.features.splice(index, 1);
                          }
                        },
                      },
                    ];
                    scope.localisertous = function() {
                      var tab = scope.tableResult.elements.features;
                      if (
                        gclayers
                          .getDrawLayer()
                          .getSource()
                          .getFeatures().length > 0
                      ) {
                        gclayers
                          .getDrawLayer()
                          .getSource()
                          .clear();
                        gclayers.clearhighLightFeatures();
                        scope.objsvisibles = 'false';
                      } else {
                        for (var j = 0; j < tab.length; j++) {
                          var obj = tab[j];
                          var format = new ol.format.GeoJSON();
                          var copy = gaJsUtils.getCleanFeature(obj);
                          var f = format.readFeature(copy);
                          gclayers
                            .getDrawLayer()
                            .getSource()
                            .addFeature(f);
                          scope.objsvisibles = 'true';
                        }
                        var extent = gclayers
                          .getDrawLayer()
                          .getSource()
                          .getExtent();
                        scope.map.getView().fit(extent, scope.map.getSize());
                      }
                    };
                    scope.closepanel();
                    scope.panelsManager.addPanel({
                      id: 'objstoadd',
                      stickToRight: true,
                      templateUrl:
                        'js/XG/widgets/mapapp/exportgeopackage/views/componentAdd.html',
                      scope: scope,
                      stickToBorder: true,
                      visible: true,
                      resizable: true,
                    });
                  });
              };

              scope.actionsyn = [
                {
                  name: 'synch',
                  icone: 'fa fa-refresh',
                  verify: function(obj) {
                    //var tab = scope.modifiedObject;
                    var tab = scope.updatedObjsForSync;
                    var tab1 = scope.deletedObjsForSync;
                    var tab2 = scope.updatedObjsGeoms;
                    if (
                      scope.verifyObjForSynhcro(obj.id, tab) ||
                      (scope.verifyObjForSynhcro(obj.id, tab2) &&
                        !scope.verifyObjForSynhcro(obj.id, tab1))
                    ) {
                      return true;
                    } else {
                      return false;
                    }
                  },
                  synchronise: function(obj) {
                    scope.compareAndSynchornise(obj);
                  },
                },
                {
                  name: 'synch',
                  icone: 'fa fa-check',
                  verify: function(obj) {
                    var tab = scope.geopackage.selectedFile.synchonisedObjs;
                    if (tab == null) {
                      return false;
                    } else {
                      if (scope.verifyObjForSynhcro(obj.id, tab)) {
                        return true;
                      } else {
                        return false;
                      }
                    }
                  },
                  synchronise: function(obj) {
                    scope.compareAndSynchornise(obj);
                  },
                },
                {
                  name: 'synch',
                  icone: 'fa fa-minus',
                  verify: function(obj) {
                    var tab = scope.deletedObjsForSync;
                    if (tab == null) {
                      return false;
                    } else {
                      if (scope.verifyObjForSynhcro(obj.id, tab)) {
                        return true;
                      } else {
                        return false;
                      }
                    }
                  },
                  synchronise: function(obj) {
                    scope.deleteObj(obj.id);
                  },
                },
                {
                  name: 'synch',
                  icone: 'fa fa-plus',
                  verify: function(obj) {
                    var tab = scope.geopackage.selectedFile.addedObjs;
                    if (tab == null) {
                      return false;
                    } else {
                      if (inArray(obj.id, tab)) {
                        return true;
                      } else {
                        return false;
                      }
                    }
                  },
                },
              ];
              scope.closepanel();
              scope.panelsManager.addPanel({
                id: 'geopackage',
                stickToRight: true,
                templateUrl:
                  'js/XG/widgets/mapapp/exportgeopackage/views/popoverDataComponent.html',
                scope: scope,
                stickToBorder: true,
                visible: true,
                resizable: true,
              });
            });
        };
        /**
         * [ajouterObjettoBDD ajout par objet]
         * @param  {[type]} id [description]
         * @return {[type]}    [description]
         */
        scope.ajouterObjettoBDD = function(id) {
          var projection = scope.map.getView().getProjection();
          scope.mapCode = projection.getCode();
          geopackageService
            .getModifiedObjectById(
              scope.geopackage.selectedFile.uid,
              id,
              scope.mapCode
            )
            .then(function(res) {
              //console.log(res.data);
              scope.objToAdd = res.data.features[0];

              var collection = {
                type: 'FeatureCollection',
                features: [],
              };

              collection.features.push({
                type: 'Feature',
                geometry: scope.objToAdd.geometry,
                properties: scope.objToAdd.properties,
              });

              var promiseAdd = EditFactory.add(
                scope.componentFti.uid,
                collection,
                scope.mapCode
              ).then(
                function(res) {
                  if (res.data.create.length == 1) {
                    var newId = res.data.create[0].id;
                    //scope.synchroniseAttach(res.data.create[0]);
                    //scope.geopackage.selectedFile.synchonisedObjs=[];
                    scope.synchroniseAttNewObj(newId);
                    if (scope.geopackage.selectedFile.addedObjs == null) {
                      scope.geopackage.selectedFile.addedObjs = [];
                    }
                    if (
                      !inArray(newId, scope.geopackage.selectedFile.addedObjs)
                    ) {
                      scope.geopackage.selectedFile.addedObjs.push(newId);
                    }
                    if (scope.geopackage.selectedFile.addedSqliteObjs == null) {
                      scope.geopackage.selectedFile.addedSqliteObjs = [];
                    }
                    if (
                      !inArray(
                        id,
                        scope.geopackage.selectedFile.addedSqliteObjs
                      )
                    ) {
                      scope.geopackage.selectedFile.addedSqliteObjs.push(id);
                    }
                    var index = scope.addedObjsForComponent.indexOf(id);
                    if (index > -1) {
                      scope.addedObjsForComponent.splice(index, 1);
                    }
                    processFactory
                      .updateProcess(scope.geopackage.selectedFile)
                      .then(
                        function(resx) {
                          require('toastr').success('ok');
                        },
                        function(res) {
                          require('toastr').error('error');
                        }
                      );
                    $rootScope.$broadcast('refreshDatatable', {
                      uid: scope.componentFti.uid,
                    });
                    require('toastr').success('ok');
                  }
                },
                function(res) {
                  require('toastr').error('error');
                }
              );
            });
        };

        scope.visulaiserGeom = function(id) {
          gclayers.clearhighLightFeatures();
          var projection = scope.map.getView().getProjection();
          scope.mapCode = projection.getCode();
          geopackageService
            .getModifiedObjectById(
              scope.geopackage.selectedFile.uid,
              id,
              scope.mapCode
            )
            .then(function(res) {
              //console.log(res.data);
              scope.objToAdd = res.data.features[0];
              if (
                gclayers
                  .getDrawLayer()
                  .getSource()
                  .getFeatures().length > 0
              ) {
                var extent = gclayers
                  .getDrawLayer()
                  .getSource()
                  .getExtent();
                scope.map.getView().fit(extent, scope.map.getSize());
                var format = new ol.format.GeoJSON();
                var copy = gaJsUtils.getCleanFeature(scope.objToAdd);
                var f = format.readFeature(copy);
                gclayers.clearhighLightFeatures();
                gclayers.addhighLightFeature(f);
              } else {
                scope.localiseGeom(scope.objToAdd);
              }
            });
        };
        scope.synchroniseAttNewObj = function(id) {
          var nameComp = id.split('.')[0];
          //scope.geopackage.selectedFile.uid
          geopackageService
            .synchroAttachementForAddedobject(
              scope.geopackage.selectedFile.uid,
              scope.componentFti.name,
              id
            )
            .then(function(res) {});
        };
        scope.localiseObjById = function(id) {
          gclayers.clearhighLightFeatures();
          var nameComp = id.split('.')[0];
          var uid = FeatureTypeFactory.getFeatureUidByName(nameComp);

          var where = 'id' + " in ('" + id + "')";
          //Remarque: les requetes spatiales ne sont pas implémentées par Query.java
          QueryFactory.data(
            uid,
            where,
            scope.map
              .getView()
              .getProjection()
              .getCode(),
            '',
            ''
          ).then(function(res) {
            if (res.data.features.length > 0) {
              mapJsUtils.localiseData(res.data.features[0], scope.map);
            }
          });
        };
        scope.visualiserAttributs = function(id) {
          var projection = scope.map.getView().getProjection();
          scope.mapCode = projection.getCode();
          geopackageService
            .getModifiedObjectById(
              scope.geopackage.selectedFile.uid,
              id,
              scope.mapCode
            )
            .then(function(res) {
              scope.objToAdd = res.data.features[0];
              scope.p = gcPopup.open({
                template:
                  'js/XG/widgets/mapapp/exportgeopackage/views/attributsView.html',
                scope: scope,
                title: 'Attributs',
                showClose: false,
              });
            });
        };
        scope.deleteObj = function(id) {
          swal(
            {
              title: 'Etes vous sure de vouloir supprimer cet objet ?',
              type: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#DD6B55',
              confirmButtonText: $filter('translate')('common.yes'),
              cancelButtonText: $filter('translate')('common.no'),
              closeOnConfirm: true,
            },
            function(isConfirm) {
              if (isConfirm) {
                EditFactory.remove(scope.componentFti.uid, id).then(
                  function(res) {
                    console.log(res.data);
                    if (res.data.delete.length == 1) {
                      var id = res.data.delete[0];
                      //scope.geopackage.selectedFile.synchonisedObjs=[];
                      if (scope.geopackage.selectedFile.deletedObjs == null) {
                        scope.geopackage.selectedFile.deletedObjs = [];
                      }
                      if (
                        !inArray(id, scope.geopackage.selectedFile.deletedObjs)
                      ) {
                        scope.geopackage.selectedFile.deletedObjs.push(id);
                      }

                      processFactory
                        .updateProcess(scope.geopackage.selectedFile)
                        .then(
                          function(resx) {
                            require('toastr').success('ok');
                          },
                          function(res) {
                            require('toastr').error('error');
                          }
                        );
                      $rootScope.$broadcast('refreshDatatable', {
                        uid: scope.componentFti.uid,
                      });
                      require('toastr').success('ok');
                    }

                    //require('toastr').success("ok");
                    //$rootScope.$broadcast('refreshDatatable', { uid: scope.componentFti.uid });
                  },
                  function(res) {
                    require('toastr').error('error');
                  }
                );
              }
            }
          );
        };
        /**
         * Verifier si un element existe dans un tableau
         * @param  {string}
         * @param  {array}
         * @return {boolean}
         */
        function inArray(elt, tab) {
          var length = tab.length;
          for (var i = 0; i < length; i++) {
            if (tab[i] == elt) return true;
          }
          return false;
        }

        scope.synchroniseAttach = function(obj) {
          console.log(scope.componentFti);
          console.log(obj);
          var atts = scope.componentFti.attributes;
          for (var i = 0; i < atts.length; i++) {
            if (
              atts[i].type == 'g2c.attachments' ||
              atts[i].type == 'g2c.attachment'
            ) {
              var attValue = obj.properties[atts[i].name];
              var id = obj.id;
              geopackageService
                .checkAttachementsObject(id, attValue)
                .then(function(result) {
                  console.log(result);
                  if (result.data == 'false') {
                    /// a completer copie du fichier
                    geopackageService
                      .updateAttachement(
                        scope.geopackage.selectedFile.uid,
                        obj.id
                      )
                      .then(function(res) {
                        console.log(res.data);
                      });
                  }
                });
            }
          }
        };

        scope.verifyObjSynchronised = function(obj) {
          var tab = scope.geopackage.selectedFile.synchonisedObjs;
          if (inArray(obj.id, tab)) {
            return true;
          } else {
            return false;
          }
        };
        scope.terminerSynchro = function(obj) {
          if (!inArray(obj.id, scope.geopackage.selectedFile.synchonisedObjs)) {
            scope.geopackage.selectedFile.synchonisedObjs.push(obj.id);
          }
          processFactory.updateProcess(scope.geopackage.selectedFile).then(
            function(resx) {
              require('toastr').success('ok');
            },
            function(res) {
              require('toastr').error('error');
            }
          );
          $rootScope.$broadcast('refreshDatatable', {
            uid: scope.componentFti.uid,
          });
        };
        /**
         * Update d'un objet
         * @param  {[type]}
         * @return {[type]}
         */
        scope.updateComponent = function(newObj) {
          if (scope.geopackage.selectedFile.synchonisedObjs == null) {
            scope.geopackage.selectedFile.synchonisedObjs = [];
          }
          if (
            scope.compareTheTwoObjects(
              scope.selectedObject,
              scope.mobileObejct
            ) &&
            scope.compareGeoms(scope.selectedObject, scope.mobileObejct)
          ) {
            if (
              !inArray(newObj.id, scope.geopackage.selectedFile.synchonisedObjs)
            ) {
              scope.geopackage.selectedFile.synchonisedObjs.push(newObj.id);
            }
          }
          scope.featUpdate = {
            type: 'FeatureCollection',
            features: [],
          };
          scope.featUpdate.features.push(newObj);
          var srid = scope.map
            ? scope.map
                .getView()
                .getProjection()
                .getCode()
            : '';
          EditFactory.update(
            scope.componentFti.uid,
            scope.featUpdate,
            srid
          ).then(
            function(res) {
              if (res.data.update.length == 1) {
                var id = res.data.update[0];
                //scope.geopackage.selectedFile.synchonisedObjs=[];
                if (scope.geopackage.selectedFile.updatedObjs == null) {
                  scope.geopackage.selectedFile.updatedObjs = [];
                }
                if (!inArray(id, scope.geopackage.selectedFile.updatedObjs)) {
                  scope.geopackage.selectedFile.updatedObjs.push(id);
                }

                processFactory
                  .updateProcess(scope.geopackage.selectedFile)
                  .then(
                    function(resx) {
                      require('toastr').success('ok');
                    },
                    function(res) {
                      require('toastr').error('error');
                    }
                  );
                $rootScope.$broadcast('refreshDatatable', {
                  uid: scope.componentFti.uid,
                });
                require('toastr').success('ok');
              }
            },
            function(res) {
              require('toastr').error('error');
            }
          );
        };

        /**
         * bloquer Synchro de tout le geopackage
         * @param  {[type]}
         * @return {[type]}
         */
        scope.blockSynchroAllGeopackage = function(geopack) {
          console.log(geopack);
          swal(
            {
              title:
                'Etes vous sure de vouloir terminer la synchronisation du geopackage?',
              //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: true,
            },
            function(isConfirm) {
              if (isConfirm) {
                //gaDomUtils.showGlobalLoader();
                geopackageService
                  .getObjectsForUpdate(geopack.uid)
                  .then(function(resu) {
                    // tous les objets a synchroniser
                    scope.allSynchObjs = resu.data;
                    var names = [];
                    scope.uids = [];
                    for (var i = 0; i < scope.allSynchObjs.length; i++) {
                      var nameC = scope.allSynchObjs[i].split('.')[0];
                      if (!inArray(nameC, names)) {
                        names.push(nameC);
                        var uidComponent = FeatureTypeFactory.getFeatureUidByName(
                          nameC
                        );
                        // tous les uids des composants ayant des objets modifies
                        scope.uids.push(uidComponent);

                        for (var i = 0; i < scope.allSynchObjs.length; i++) {
                          if (
                            !inArray(
                              scope.allSynchObjs[i],
                              geopack.synchonisedObjs
                            )
                          ) {
                            geopack.synchonisedObjs.push(scope.allSynchObjs[i]);
                          }
                        }
                        geopack.synchronised = true;
                        processFactory.updateProcess(geopack).then(
                          function(resx) {
                            require('toastr').success('ok');
                          },
                          function(res) {
                            require('toastr').error('error');
                          }
                        );
                        // raffraichire la datatable des composants modifies
                        for (var k = 0; k < scope.uids.length; k++) {
                          $rootScope.$broadcast('refreshDatatable', {
                            uid: scope.uids[k],
                          });
                        }
                      }
                    }
                  });
              }
            }
          );
        };

        /**
         * Synchroniser tout le geopackage
         * @param  {[type]}
         * @return {[type]}
         */
        scope.synchroAllGeopackage = function(geopack) {
          console.log(geopack);
          swal(
            {
              title:
                'Etes vous sure de vouloir synchorniser tous le géopackage?',
              //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: true,
            },
            function(isConfirm) {
              if (isConfirm) {
                gaDomUtils.showGlobalLoader();
                geopackageService
                  .getObjectsForUpdate(geopack.uid)
                  .then(function(resu) {
                    geopackageService.getObjectsForDelete(geopack.uid).then(
                      function(resd) {
                        scope.objsForDelete = resd.data;

                        // tous les objets a synchroniser
                        scope.allSynchObjs = resu.data;
                        var names = [];
                        scope.uids = [];
                        for (var i = 0; i < scope.allSynchObjs.length; i++) {
                          var nameC = scope.allSynchObjs[i].split('.')[0];
                          if (!inArray(nameC, names)) {
                            names.push(nameC);
                            var uidComponent = FeatureTypeFactory.getFeatureUidByName(
                              nameC
                            );
                            // tous les uids des composants ayant des objets modifies
                            scope.uids.push(uidComponent);
                          }
                        }
                        //console.log(scope.uids);
                        var projection = scope.map.getView().getProjection();
                        var mapCode = projection.getCode();
                        geopackageService
                          .synchroGeopackage(geopack.uid, mapCode)
                          .then(function(result) {
                            console.log(result);
                            require('toastr').success(
                              'Synchronisation du geopackage'
                            );
                            for (
                              var i = 0;
                              i < scope.allSynchObjs.length;
                              i++
                            ) {
                              if (
                                !inArray(
                                  scope.allSynchObjs[i],
                                  geopack.synchonisedObjs
                                )
                              ) {
                                if (scope.allSynchObjs[i].indexOf('-') == -1) {
                                  geopack.synchonisedObjs.push(
                                    scope.allSynchObjs[i]
                                  );
                                }
                              }
                            }

                            for (var k = 0; k < result.data.length; k++) {
                              if (result.data[k].indexOf('-') !== -1) {
                                geopack.addedSqliteObjs.push(result.data[k]);
                              } else {
                                geopack.addedObjs.push(result.data[k]);
                              }
                            }
                            if (geopack.deletedObjs == null) {
                              geopack.deletedObjs = [];
                            }
                            for (
                              var j = 0;
                              j < scope.objsForDelete.length;
                              j++
                            ) {
                              var id = scope.objsForDelete[j];

                              if (!inArray(id, geopack.deletedObjs)) {
                                geopack.deletedObjs.push(id);
                              }
                            }
                            geopack.synchronised = true;
                            processFactory.updateProcess(geopack).then(
                              function(resx) {
                                require('toastr').success('ok');
                              },
                              function(res) {
                                require('toastr').error('error');
                              }
                            );
                            // raffraichire la datatable des composants modifies
                            for (var k = 0; k < scope.uids.length; k++) {
                              $rootScope.$broadcast('refreshDatatable', {
                                uid: scope.uids[k],
                              });
                            }
                          });
                        gaDomUtils.hideGlobalLoader();
                      },
                      function(res) {
                        require('toastr').error('error synchro');
                        gaDomUtils.hideGlobalLoader();
                      }
                    );
                  });
              }
            }
          );
        };
        scope.verifyCompSynchronised = function(geopackage) {
          if (geopackage.selectedFile.synchonisedComponents == null) {
            geopackage.selectedFile.synchonisedComponents = [];
          }
          if (
            inArray(
              geopackage.componentSelected,
              geopackage.selectedFile.synchonisedComponents
            )
          ) {
            return true;
          } else {
            return false;
          }
        };

        /**
         * terminer et bloquer la synchronisation d'un composant
         * @param  {[type]}
         * @return {[type]}
         */
        scope.blockSynchroByComponent = function(geopackage) {
          swal(
            {
              title:
                'Etes vous sure de vouloir terminer la sunchronisation de ce composant?',
              //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: true,
            },
            function(isConfirm) {
              if (isConfirm) {
                geopackageService
                  .getObjectsForUpdate(geopackage.selectedFile.uid)
                  .then(function(resu) {
                    // tous les objets modifies
                    scope.allModifiedObjs = resu.data;
                    scope.uidComponent = FeatureTypeFactory.getFeatureUidByName(
                      scope.geopackage.componentSelected
                    );
                    scope.componentFti = FeatureTypeFactory.getFeatureByUid(
                      scope.uidComponent
                    );
                    for (var i = 0; i < scope.allModifiedObjs.length; i++) {
                      var nameC = scope.allModifiedObjs[i].split('.')[0];
                      if (
                        !inArray(
                          scope.allModifiedObjs[i],
                          geopackage.selectedFile.synchonisedObjs
                        ) &&
                        nameC == scope.componentFti.name
                      ) {
                        geopackage.selectedFile.synchonisedObjs.push(
                          scope.allModifiedObjs[i]
                        );
                      }
                    }
                    if (
                      !inArray(
                        scope.componentFti.name,
                        geopackage.selectedFile.synchonisedComponents
                      )
                    ) {
                      geopackage.selectedFile.synchonisedComponents.push(
                        scope.componentFti.name
                      );
                    }
                    processFactory.updateProcess(geopackage.selectedFile).then(
                      function(resx) {
                        require('toastr').success('ok');
                      },
                      function(res) {
                        require('toastr').error('error');
                      }
                    );
                    $rootScope.$broadcast('refreshDatatable', {
                      uid: scope.componentFti.uid,
                    });
                  });
              }
            }
          );
        };

        /**
         * Synchroniser tous les objets d'un composant d'un geopackage
         * @param  {[type]}
         * @return {[type]}
         */
        scope.synchroByComponent = function(geopackage) {
          swal(
            {
              title:
                'Etes vous sure de vouloir mettre à jour tous les objets ?',
              //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: true,
            },
            function(isConfirm) {
              if (isConfirm) {
                gaDomUtils.showGlobalLoader();
                geopackageService
                  .getObjectsForUpdate(geopackage.selectedFile.uid)
                  .then(function(resu) {
                    geopackageService
                      .getObjectsForDelete(geopackage.selectedFile.uid)
                      .then(
                        function(resd) {
                          scope.objsForDelete = resd.data;

                          // tous les objets modifies
                          scope.allModifiedObjs = resu.data;
                          scope.uidComponent = FeatureTypeFactory.getFeatureUidByName(
                            scope.geopackage.componentSelected
                          );
                          scope.componentFti = FeatureTypeFactory.getFeatureByUid(
                            scope.uidComponent
                          );
                          var projection = scope.map.getView().getProjection();
                          var mapCode = projection.getCode();
                          geopackageService
                            .synchroByComponent(
                              geopackage.selectedFile.uid,
                              scope.componentFti.name,
                              mapCode
                            )
                            .then(function(result) {
                              require('toastr').success(
                                'Sycnhronisation des objets' +
                                  scope.componentFti.name
                              );

                              console.log(scope.componentFti.uid);

                              // enregistrer les objets synchronises du geopackage
                              for (
                                var i = 0;
                                i < scope.allModifiedObjs.length;
                                i++
                              ) {
                                var nameC = scope.allModifiedObjs[i].split(
                                  '.'
                                )[0];

                                if (
                                  !inArray(
                                    scope.allModifiedObjs[i],
                                    geopackage.selectedFile.synchonisedObjs
                                  ) &&
                                  nameC == scope.componentFti.name
                                ) {
                                  if (
                                    scope.allModifiedObjs[i].indexOf('-') == -1
                                  ) {
                                    geopackage.selectedFile.synchonisedObjs.push(
                                      scope.allModifiedObjs[i]
                                    );
                                  }
                                }
                              }

                              if (
                                !inArray(
                                  scope.componentFti.name,
                                  geopackage.selectedFile.synchonisedComponents
                                )
                              ) {
                                geopackage.selectedFile.synchonisedComponents.push(
                                  scope.componentFti.name
                                );
                              }
                              for (var k = 0; k < result.data.length; k++) {
                                if (result.data[k].indexOf('-') !== -1) {
                                  scope.geopackage.selectedFile.addedSqliteObjs.push(
                                    result.data[k]
                                  );
                                } else {
                                  scope.geopackage.selectedFile.addedObjs.push(
                                    result.data[k]
                                  );
                                }
                              }

                              if (geopackage.selectedFile.deletedObjs == null) {
                                geopackage.selectedFile.deletedObjs = [];
                              }
                              for (
                                var j = 0;
                                j < scope.objsForDelete.length;
                                j++
                              ) {
                                var id = scope.objsForDelete[j];
                                var nameComp = id.split('.')[0];
                                if (
                                  !inArray(
                                    id,
                                    geopackage.selectedFile.deletedObjs
                                  ) &&
                                  nameComp == scope.componentFti.name
                                ) {
                                  geopackage.selectedFile.deletedObjs.push(id);
                                }
                              }
                              processFactory
                                .updateProcess(geopackage.selectedFile)
                                .then(
                                  function(resx) {
                                    require('toastr').success('ok');
                                  },
                                  function(res) {
                                    require('toastr').error('error');
                                  }
                                );
                            });

                          $rootScope.$broadcast('refreshDatatable', {
                            uid: scope.componentFti.uid,
                          });

                          gaDomUtils.hideGlobalLoader();
                        },
                        function(res) {
                          require('toastr').error('error synchro');
                          gaDomUtils.hideGlobalLoader();
                        }
                      );
                  });
              }
            }
          );
        };

        scope.createName = function(x) {
          return x.file + ' | ' + x.uid.substring(0, 6);
        };

        scope.refreshMbtilesList = function() {
          processFactory.getProcessByUsertype('mbtiles').then(
            function(res) {
              if (res && res.data && res.data.length > 0)
                scope.mbtiles = res.data.filter(function(x) {
                  if (x && x.etat && x.etat === 'FINISHED') return x;
                });
            },
            function(res) {
              console.error('unable to get mbtiles');
            }
          );
        };

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

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

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

        scope.openInfo = function(rapport) {
          //scope.edit_resource = scope.geopackage.selectedFile;
          scope.edit_resource = rapport;

          ngDialog.open({
            template: 'js/XG/modules/process/views/info.geopackage.html',
            className: 'ngdialog-theme-plain  width400 height50 miniclose',
            closeByDocument: false,
            scope: scope,
          });
        };
        scope.getBilanSynchro = function(rapport) {
          //scope.edit_resource = scope.geopackage.selectedFile;
          scope.edit_resource = rapport;
          gcPopup.open({
            template:
              'js/XG/widgets/mapapp/exportgeopackage/views/bilanSynchro.html',
            scope: scope,
            title: 'Bilan synchronisation',
            showClose: false,
          });
        };
      },
    };
  };

  imexGeopackage.$inject = [
    'geopackageService',
    'FeatureTypeFactory',
    '$filter',
    'gcStyleFactory',
    'gaDomUtils',
    'SelectManager',
    '$interval',
    '$rootScope',
    'gcInteractions',
    'SridFactory',
    'processFactory',
    '$location',
    'ngDialog',
    'gaUrlUtils',
    'ngTableParams',
    'gclayers',
    '$timeout',
    'extendedNgDialog',
    'EditFactory',
    'QueryFactory',
    'gcPopup',
    'gaJsUtils',
    'mapJsUtils'
  ];
  return imexGeopackage;
});
