'use strict';
define(function() {
  var sitesCtrl = function(
    $scope,
    FeatureTypeFactory,
    gcWMS,
    ConfigFactory,
    gclayers,
    $rootScope,
    $location,
    extendedNgDialog,
    ngDialog,
    panelsManager,
    SirocoFactory,
    gaDomUtils,
    QueryFactory,
    gaJsUtils,
    $timeout,
    ParametersFactory,
    ReportFactory
  ) {
    var sirocoCfg = JSON.parse(sessionStorage.getItem('sirocoCfg'));
    $scope.map = new ol.Map({
      layers: [new ol.layer.Tile({ source: new ol.source.OSM() })],
      controls: ol.control.defaults({
        attribution: false,
      }),
      target: 'map_sites',
      view: new ol.View({
        zoom: 14,
      }),
      ol3Logo: false,
    });

    $scope.currentChantier = {};
    /*$scope.$on('siroco_charger_canas_chantier', function (event,args) {

            if($scope.listChantiers.chantiers){
                var chantier =  $scope.listChantiers.chantiers[0];
                var chantierId = chantier.id;
                QueryFactory.relation(chantiersFeature.uid, "*", chantierId, "").then(function(res) {

                });
            }else{
                console.log('new chantier...');
            }

            $rootScope.$broadcast('siroco_charger_canas_chantier#ended');
        });*/

    /**
     * calculer_chantier from the chantier form (intervention)
     */
    $scope.$on('siroco_imprimer_chantier', function(event, args) {
      SirocoFactory.getRapportChantier(args.chantiers[0], true);
    });

    /**
     * calculer_chantier from the chantier form (intervention)
     */
    $scope.$on('siroco_calculer_chantier', function(event, args) {
      // chantier id
      var chantierId = args.current.id;

      if (angular.isDefined(chantierId)) {
        gaDomUtils.showGlobalLoader();
        SirocoFactory.calculerchantier(sirocoCfg.appname, chantierId).then(
          function(res) {
            if (!res.data.ok) {
              require('toastr').error(
                res.data.errorMessage,
                'Erreur lors du calcul des données du chantier',
                {
                  closeButton: true,
                  timeOut: '0',
                  extendedTimeOut: '0',
                  positionClass: 'toast-bottom-full-width',
                }
              );
              gaDomUtils.hideGlobalLoader();
              return;
            }
            // get all the new information and set it in the form
            QueryFactory.get(chantiersFeature.uid, chantierId).then(function(
              res
            ) {
              $rootScope.$broadcast('siroco_calculer_chantier#ended');
              args.current.properties = res.data.features[0].properties;
              gaDomUtils.hideGlobalLoader();
              // clean the drawlayer
              gclayers
                .getDrawLayer()
                .getSource()
                .clear();
              // refresh style
              $rootScope.$broadcast('gcOperationalLayerChange', '', 'applyall');
            });
          }
        );
      } else {
        console.log('no id');
      }
    });

    //console.log('woot');

    panelsManager.init();
    $scope.panelsManager = panelsManager;
    $scope.canToggleCanasStyle = false;
    var chantiersFeature;
    var layersToDisplay = [
      sirocoCfg.layersNames.cana_aep,
      sirocoCfg.layersNames.fuite,
      sirocoCfg.layersNames.chantier,
    ];

    gclayers.clearOperationalLayer();
    FeatureTypeFactory.get().then(function() {
      FeatureTypeFactory.resources.featuretypes.forEach(function(fType) {
        var ind = 0;
        if (fType.storeName == sirocoCfg.mainConfig.datastore) {
          if (fType.geographic && fType.published) {
            if (layersToDisplay.indexOf(fType.name) != -1) {
              var l = gcWMS.getOlLayerFromFeaturetypeInfo(fType, ind);
              l.visible = true;
              l.selected = true;

              ind++;
              gclayers.addOperationalLayerg2c(l);

              // get chantier feature
              if (fType.name == sirocoCfg.layersNames.chantier) {
                chantiersFeature = fType;
              }

              // zoom on extent of cana
              if (fType.name == sirocoCfg.layersNames.cana_aep) {
                var layers = gclayers.getOperationalLayerg2c();
                angular.forEach(layers, function(l) {
                  if (l.fti.uid == fType.uid) {
                    if (fType.styles.indexOf('AEP_CANA_IMPORTANCE') != -1) {
                      l.style = 'AEP_CANA_IMPORTANCE';
                      $scope.canToggleCanasStyle = true;
                      $rootScope.$broadcast(
                        'gcOperationalLayerChange',
                        '',
                        'applyall'
                      );
                    }
                  }
                });

                /*   var canaLayer = gclayers.getOperationalLayer().slice(-1)[0];
                                var src = canaLayer.getSource();
                                console.log(src);
                                var params = src.getParams();
                                console.log(params);
*/
                FeatureTypeFactory.getExtent(
                  fType.uid,
                  $scope.map
                    .getView()
                    .getProjection()
                    .getCode()
                ).then(function(res) {
                  var bbox = res.data;
                  $scope.map.getView().fit(bbox, $scope.map.getSize());
                });
              }
            }
          }
        }
        //
      });

      $rootScope.$broadcast('gcOperationalLayerOnInit');
    });

    $scope.isOpenChantier = false;

    /**
     * Add Chantier form
     */
    $scope.addChantier = function() {
      // reset
      $scope.listChantiers = {};
      $scope.closeListChantiers();

      ConfigFactory.get('forms', 'chantier.form', sirocoCfg.appname).then(
        function(res) {
          //link.template =  res.data;
          $scope.currentChantier = {};
          $scope.ftemplatedata = res.data;
          $scope.isOpenChantier = true;

          var chantierDialog = extendedNgDialog.open({
            template:
              'js/XG/widgets/sirocoapp/init/views/modals/modal.chantier.html',
            className: 'ngdialog-theme-plain width800 nopadding miniclose',
            closeByDocument: false,
            scope: $scope,
            title: 'Édition de Chantier',
            draggable: true,
          });

          chantierDialog.closePromise.then(function(data) {
            $scope.isOpenChantier = false;
          });
        }
      );
    };

    /**
     * closepanel
     */
    $scope.closeListChantiers = function() {
      $scope.panelsManager.removePanel('list_chantiers');
    };

    /**
     * ListChantiers
     */
    $scope.ListChantiers = function() {
      ConfigFactory.get(
        'forms',
        'liste_chantiers.form',
        sirocoCfg.appname
      ).then(function(res) {
        $scope.listChantiers = {};
        $scope.currentlink = {
          template: res.data,
        };

        $scope.closeListChantiers();
        $scope.panelsManager.addPanel({
          id: 'list_chantiers',
          stickToRight: true,
          templateUrl:
            'js/XG/widgets/sirocoapp/init/views/modals/modal.list_chantiers.html',
          scope: $scope,
          stickToBorder: true,
          visible: true,
        });
      });
    };
  };

  sitesCtrl.$inject = [
    '$scope',
    'FeatureTypeFactory',
    'gcWMS',
    'ConfigFactory',
    'gclayers',
    '$rootScope',
    '$location',
    'extendedNgDialog',
    'ngDialog',
    'panelsManager',
    'SirocoFactory',
    'gaDomUtils',
    'QueryFactory',
    'gaJsUtils',
    '$timeout',
    'ParametersFactory',
    'ReportFactory',
  ];
  return sitesCtrl;
});
