'use strict';
define(function() {
  var ancBibliothequeElementsFiliere = function(
    gaDomUtils,
    QueryFactory,
    ngDialog,
    AncAppFactory,
    $timeout,
    gaJsUtils
  ) {
    return {
      templateUrl:
        'js/XG/widgets/ancapp/main/views/directives/anc_bibliotheque_elements_filiere.html',
      restrict: 'EA',
      scope: {
        apptype: '=?',
        choose: '&?', // choix d'une representation
        disabledModeles: '=?', // permet de disable certains modeles, si deja associes par ex
        elementFiliereCourant: '=?', // l'element de filiere a partir duquel on a ouvert la bibliotheque
      },
      link: function(scope, elt, attrs, ctrl) {
        var dndrop;
        // configuration de la bibliotheque
        scope.bibliCfg = {
          mode: 'picker',
        };

        $timeout(function() {
          // ✪ Dragula bibliotheque !
          if (typeof dndrop == 'undefined') {
            dndrop = dragula($('.mlist .content').toArray(), {
              revertOnSpill: true,
              moves: function(el, container, handle) {
                var isDraggable =
                  el.attributes.class.nodeValue.indexOf('mlistitem') !== -1;
                if (scope.bibliCfg.mode != 'category_editor')
                  isDraggable = false;
                if (!isDraggable) {
                  return false;
                }
                return true;
              },
            }).on('drop', function(el, container, source) {
              // doit etre drop dans un container
              if (container == null) return false;

              var elementId = el.attributes['data-uid'].nodeValue;
              var destContainerIdx = container.attributes['data-idx'].nodeValue;
              var sourceContainerIdx = source.attributes['data-idx'].nodeValue;

              // drop dans la meme boite
              if (sourceContainerIdx == destContainerIdx) return false;

              console.log(scope.categoriesBibliotheque);

              $timeout(function() {
                var elementFound = false,
                  sourceElements =
                    scope.categoriesBibliotheque[sourceContainerIdx].elements,
                  destElements =
                    scope.categoriesBibliotheque[destContainerIdx].elements;

                // console.log(sourceElements);
                // console.log(destElements);
                // console.log(sourceElements.length);
                // console.log(destElements.length);

                var _tmp = sourceElements.filter(function(obj) {
                  return obj.id == elementId;
                });
                if (_tmp.length) elementFound = _tmp[0];

                // push
                destElements.push(angular.copy(elementFound));
                // filter
                scope.categoriesBibliotheque[
                  sourceContainerIdx
                ].elements = sourceElements.filter(function(obj) {
                  return obj.id !== elementId;
                });

                console.log(sourceElements);
                console.log(destElements);
                console.log(sourceElements.length);
                console.log(destElements.length);

                // useless
                el.remove();
              });
            });
          }
        }, 1000);

        scope.alreadyPickedModeles = [];
        /**
         * setDisabledModeles
         */
        var setDisabledModeles = function() {
          scope.alreadyPickedModeles = [];
          if (
            angular.isDefined(scope.disabledModeles) &&
            scope.disabledModeles.length
          ) {
            // on ajoute une propriete already_selected sur les ef
            for (var i in scope.disabledModeles) {
              scope.categoriesBibliotheque.map(function(cat) {
                for (var j in cat.elements) {
                  if (
                    cat.elements[j].properties.identifiant ==
                    scope.disabledModeles[i].modele
                  ) {
                    cat.elements[j].already_picked = true;
                    scope.alreadyPickedModeles.push(
                      cat.elements[j].properties.nom
                    );
                  }
                }
              });
            }
          }
        };

        scope.pickedModele = {};
        scope.addCategorie = function() {
          scope.categoriesBibliotheque.push({
            title: '-',
            elements: [],
          });

          $timeout(function() {
            // Add the dropZones as they are added to the DOM
            Array.prototype.forEach.call($('.mlist .content'), function(el) {
              console.log(el);

              dndrop.containers.push(el);
            });
          }, 0);
        };

        var getCategorieCfgToSave = function() {
          var categories = [];
          for (var x in scope.categoriesBibliotheque) {
            categories.push({
              title: scope.categoriesBibliotheque[x].title,
              elements: scope.categoriesBibliotheque[x].elements.map(function(
                x
              ) {
                return x.id;
              }),
            });
          }

          return angular.copy(categories);
        };

        var svgCategoryCfg;
        /**
         * saveCategories
         */
        scope.saveCategories = function() {
          var categories = getCategorieCfgToSave();
          AncAppFactory.appCfg.main.properties.filieresVectorielles.categories = categories;
          AncAppFactory.updateAppCfg();

          svgCategoryCfg = angular.copy(categories);
          scope.bibliCfg.mode = 'picker';
        };

        /**
         * activateCategoryEditor
         */
        scope.activateCategoryEditor = function() {
          svgCategoryCfg = getCategorieCfgToSave();
          scope.bibliCfg.mode = 'category_editor';
        };
        /**
         * cancelCategories
         */
        scope.cancelCategories = function() {
          var ans = confirm(
            'Êtes-vous certain de vouloir quitter sans enregister ?'
          );
          if (ans) {
            scope.bibliCfg.mode = 'picker';
            refreshListeEf();
          }
        };

        scope.removeCategory = function(idx) {
          var ans = confirm(
            'Êtes-vous certain de vouloir supprimer cette catégorie ?'
          );
          if (ans) {
            scope.categoriesBibliotheque.splice(idx, 1);
          }
        };
        scope.categoriesBibliotheque = false;

        /**
         * refreshListeEf
         * @param {*} redrawId l' id de la feature a refresh dans ancEditDessinFiliere, eventuellement
         */
        var refreshListeEf = function(redrawId) {
          scope.bibliEf = {};
          gaDomUtils.showGlobalLoader();
          QueryFactory.data('kis_anc_bibliotheque_ef', '', 'EPSG:2154').then(
            function(res) {
              gaDomUtils.hideGlobalLoader();
              scope.bibliEf = res.data.features;

              var listeEfParId = {};
              res.data.features.map(function(b) {
                listeEfParId[b.id] = {
                  item: b,
                  found: false,
                };
              });
              // alimentation des categories
              //if (!scope.categoriesBibliotheque) {
              var cmp = angular.copy(
                AncAppFactory.appCfg.main.properties.filieresVectorielles
                  .categories
              );

              var final = [];
              for (var i in cmp) {
                final[i] = {
                  title: cmp[i].title,
                  elements: [],
                };
                cmp[i].elements.map(function(x) {
                  if (angular.isDefined(listeEfParId[x])) {
                    listeEfParId[x].found = true;
                    final[i].elements.push(listeEfParId[x].item);
                  } else {
                    console.log(
                      '%c --- MANQUANT ::: ' + listeEfParId[x],
                      'background: #f00; color: #fff'
                    );
                  }
                });
              }

              // }
              //  console.log(cmp);

              // si des elements ne sont pas trouves
              var notFound = [];
              for (var i in listeEfParId) {
                if (!listeEfParId[i].found) notFound.push(listeEfParId[i].item);
              }

              if (notFound.length) {
                final[final.length] = {
                  title: 'Sans catégorie',
                  elements: notFound,
                };
              }
              scope.categoriesBibliotheque = final;

              setDisabledModeles();

              if (redrawId) {
                res.data.features.map(function(b) {
                  if (b.id == redrawId) {
                    scope.$broadcast('refreshCurrentDessinEf', {
                      modele: b,
                    });
                  }
                });
              }
            },
            function() {
              require('toastr').error(
                'Erreur lors de la récupération de la bibliothèque.'
              );
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        refreshListeEf();

        var editorDialog;
        scope.showEditor = function(modele, isDuplication) {
          scope.svgEditorData = {
            scale: 0.02,
            featureId: null,
          };

          // edition d'un modele existant
          if (modele) {
            scope.svgEditorData.nom = modele.properties.nom;
            scope.svgEditorData.identifiant = modele.properties.identifiant;

            // duplication = creation
            if (isDuplication) {
              scope.svgEditorData.nom += '_copie';
              scope.svgEditorData.identifiant = 'biblief_' + gaJsUtils.guid();
              // update
            } else {
              scope.svgEditorData.featureId = modele.id;
            }

            scope.svgEditorData.svgToload = modele.properties.svg;
          } else {
            // generation d'un identifiant
            scope.svgEditorData.identifiant = 'biblief_' + gaJsUtils.guid();
          }

          editorDialog = ngDialog.open({
            template:
              'js/XG/widgets/ancapp/main/views/modals/modal.svg_ef_editor.html',
            className: 'ngdialog-theme-plain fullScreen nopadding miniclose',
            closeByDocument: false,
            scope: scope,
            preCloseCallback: function() {
              refreshListeEf();
            },
          });
        };

        /**
         * saveEfVectoriel
         */
        scope.saveEfVectoriel = function() {
          // suppression des : ou des ; qui sont utilises dans le mapping
          if (scope.svgEditorData.nom.indexOf(':') !== false) {
            scope.svgEditorData.nom = scope.svgEditorData.nom.replace(
              /:/g,
              '_'
            );
          }
          if (scope.svgEditorData.nom.indexOf(';') !== false) {
            scope.svgEditorData.nom = scope.svgEditorData.nom.replace(
              /;/g,
              '_'
            );
          }

          // si identifiant existe deja -> erreur
          var err = false;
          if (!scope.svgEditorData.featureId) {
            scope.bibliEf.map(function(x) {
              if (!err) {
                if (x.properties.nom == scope.svgEditorData.nom) {
                  require('toastr').warning('Ce nom est déja utilisé.');
                  err = true;
                }
                // if (x.properties.identifiant == scope.svgEditorData.identifiant) {
                //     require('toastr').warning("Cet identifiant est déja utilisé.");
                //     err = true;
                // }
              }
            });
          }

          if (err) return;
          gaDomUtils.showGlobalLoader();

          try {
            var svg = scope.svgEditorData.svg.trim().replace(/[\n\r]+/g, '');

            AncAppFactory.addbiblief({
              nom: scope.svgEditorData.nom,
              identifiant: scope.svgEditorData.identifiant,
              wkt: SVGtoWKT.convert(svg),
              svg: svg,
              scale: scope.svgEditorData.scale,
              featureId: scope.svgEditorData.featureId,
            }).then(
              function(res) {
                require('toastr').success(
                  scope.svgEditorData.nom + ' enregistré.',
                  '',
                  {
                    positionClass: 'toast-bottom-left',
                  }
                );

                gaDomUtils.hideGlobalLoader();
                refreshListeEf(scope.svgEditorData.featureId);
                scope.svgEditorData.featureId = res.data;
              },
              function() {
                require('toastr').error("Erreur lors de l'enregistrement.");
                gaDomUtils.hideGlobalLoader();
              }
            );
          } catch (error) {
            console.log(error);
            require('toastr').error("Erreur lors de l'enregistrement.");
            gaDomUtils.hideGlobalLoader();
          }
        };

        /**
         * Choisir
         */
        scope.do_choose = function(x) {
          scope.choose({
            data: scope.pickedModele.x,
          });
          $timeout(function() {
            setDisabledModeles();
            require('toastr').success(
              scope.pickedModele.x.properties.nom + ' sélectionné.',
              '',
              {
                positionClass: 'toast-bottom-left',
              }
            );
          });
        };
      },
    };
  };

  ancBibliothequeElementsFiliere.$inject = [
    'gaDomUtils',
    'QueryFactory',
    'ngDialog',
    'AncAppFactory',
    '$timeout',
    'gaJsUtils',
  ];
  return ancBibliothequeElementsFiliere;
});
