Subversion Repositories eFlore/Applications.cel

Rev

Rev 168 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package org.tela_botanica.client.vues;

import java.util.Comparator;
import java.util.Iterator;

import org.tela_botanica.client.interfaces.Filtrable;
import org.tela_botanica.client.interfaces.Rafraichissable;
import org.tela_botanica.client.modeles.EntiteGeographiqueObservation;
import org.tela_botanica.client.modeles.ListeEntiteGeographiqueObservation;
import org.tela_botanica.client.modeles.Observation;
import org.tela_botanica.client.observation.ObservationMediateur;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Label;
import com.gwtext.client.data.Node;
import com.gwtext.client.data.NodeTraversalCallback;
import com.gwtext.client.data.Tree;
import com.gwtext.client.data.event.NodeListenerAdapter;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.PanelListenerAdapter;
import com.gwtext.client.widgets.tree.TreeNode;
import com.gwtext.client.widgets.tree.TreePanel;
import com.gwtext.client.widgets.tree.event.TreeNodeListenerAdapter;
import com.gwtext.client.widgets.tree.event.TreePanelListenerAdapter;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.ExtElement;

/**
 * fenêtre de recherche affichant l'arbre des mots clés en lecture et un bouton
 * cliquable
 * 
 * @author aurelien
 * 
 */
public class ArbreEntiteGeographiqueObservationFiltreVue extends Panel implements Rafraichissable,
                Filtrable {

        /**
         * Le médiateur associé à la vue
         */
        private ObservationMediateur    observationMediateur            = null;

        /**
         * Les localites en cours
         */
        private String entitesGeographiquesEncours = "";

        /**
         * Le treepanel qui affiche l'arbre
         */
        private TreePanel arbreEntitesGeographiques = null;



        /**
         * La structure de donnees qui stocke l'arbre. Utilisee a ce niveau car trop liee a la vue
         */
        
        private Tree donneeEntitesGeographiques = new Tree();;
        
        /**
         * booléen d'initialisation
         */
        private boolean estInstancie = false;

        /**
         * booléen d'etat
         */
        private boolean filtreModifie = false;
        
        private boolean arbreCharge = false ;

        private String nomFiltre = "" ;
        
        /**
         * Constructeur sans argument (privé car ne doit pas être utilisé)
         */
        @SuppressWarnings("unused")
        private ArbreEntiteGeographiqueObservationFiltreVue() {
                super();
        }

        /**
         * Constructeur avec paramètres
         * 
         * @param im
         *            le médiateur à associer
         */
        public ArbreEntiteGeographiqueObservationFiltreVue(ObservationMediateur obs) {

                // on crée le panel
                super("Localités");
                
                this.observationMediateur = obs;

                arbreEntitesGeographiques = new TreePanel();

                this.setPaddings(5);

                this.setCollapsible(true);
                this.setAutoWidth(true);
                
                if (GWT.isScript()) {
                        setAutoScroll(true);
                }


                // on ajoute les listeners
                ajouterListenersPanel();
                estInstancie = false;
        }

        /**
         * Ajoute les listeners pour le rendu du panel
         */
        private void ajouterListenersPanel() {
                  this.addListener(new PanelListenerAdapter() {

                        // on instancie réellement les composants au moment du rendu pour
                        // accélérer l'affichage
                        // et éviter des bugs
                        public void onRender(Component component) {

                                // on interdit le drag and drop dans l'arbre
                                arbreEntitesGeographiques.setEnableDD(false);
                                arbreEntitesGeographiques.setId("x-view-tree-filter-entity");
                                arbreEntitesGeographiques.setAutoWidth(false);

                                // on crée une racine pour l'arbre
                                TreeNode root = new TreeNode("Localités");
                                root.setId("racine_entite");
                                String[] usObject = { "Localités" };
                                root.setUserObject(usObject);

                                arbreEntitesGeographiques.setRootNode(root);
                                arbreEntitesGeographiques.setRootVisible(true);
                                arbreEntitesGeographiques.setBorder(false);
                                root.setExpandable(true) ;

                                add(arbreEntitesGeographiques);

                                // on ajoute les listeners d'évenements
                                ajouterListeners();

                                
                                // enfin on considère le composant comme instancié
                                estInstancie = true;

                                
                        }

                });
        }

        
        
        /**
         * ajoute les listeners pour les boutons et le cochage des entites
         */
        private void ajouterListeners() {
                
                arbreEntitesGeographiques.addListener(new TreePanelListenerAdapter() {
                        
                        public void onClick(TreeNode node, EventObject e) {
                                
                                nomFiltre = "" ;
                                entitesGeographiquesEncours = "" ;
                                String nomPere = "" ;
                                String nomGrandPere = "" ;
                                
                                switch(node.getDepth()) 
                                {
                                        case 0:
                                                if(!arbreCharge)
                                                {
                                                        arbreEntitesGeographiques.getRootNode().expand();
                                                }
                                                else 
                                                {
                                                        observationMediateur.obtenirNombreObservation() ;
                                                }
                                                return ;
                                        case 3: nomFiltre += "lieudit,location,id_location";
                                                nomPere = ((String[])node.getParentNode().getUserObject())[0] ;
                                                nomGrandPere = ((String[])node.getParentNode().getParentNode().getUserObject())[0] ;
                                                entitesGeographiquesEncours += node.getText()+","+nomPere+","+nomGrandPere ;
                                                break;
                                        case 2: nomFiltre += "location,id_location"; 
                                                nomPere = ((String[])node.getParentNode().getUserObject())[0] ;
                                                entitesGeographiquesEncours += node.getText()+","+nomPere ;
                                                break;
                                        case 1: nomFiltre += "id_location"; 
                                                entitesGeographiquesEncours += node.getText() ;
                                                break;
                                        default: 
                                                break;
                                }
                                
                                filtreModifie = true ;
                                observationMediateur.obtenirNombreObservation() ;
                                
                        }
                        
                }) ;
                
                arbreEntitesGeographiques.getRootNode().addListener(new TreeNodeListenerAdapter() {
                        
                        public void onExpand(Node node) {
                                if(!arbreCharge)
                                {
                                        observationMediateur.obtenirListeEntiteGeographique() ;
                                        arbreCharge = true ;
                                }
                        }
                        
                }) ;
        }
        
        public void initialiser() {
                
                arbreCharge = false ;
                arbreEntitesGeographiques.collapseAll();
                // on vide l'ancien arbre
                Node[] rootChild = arbreEntitesGeographiques.getRootNode().getChildNodes();
                for (int i = 0; i < rootChild.length; i++) {
                        
                        rootChild[i].remove();
                }
                
                arbreEntitesGeographiques.getRootNode().addListener(new TreeNodeListenerAdapter() {
                        
                        public void onExpand(Node node) {
                                if(!arbreCharge)
                                {
                                        observationMediateur.obtenirListeEntiteGeographique() ;
                                        arbreCharge = true ;
                                }
                        }
                        
                }) ;
        }

        /**
         * Méthode héritée de l'interface rafraichissable
         */
        public void rafraichir(Object nouvelleDonnees,
                        boolean repandreRaffraichissement) {

                
                if (nouvelleDonnees instanceof ListeEntiteGeographiqueObservation) {
                
                        String id_location=null;
                        String location=null;
                        String lieuDit=null;
                        
                        ListeEntiteGeographiqueObservation data = (ListeEntiteGeographiqueObservation) nouvelleDonnees ;
                
                                // on crée un arbre vide
                                Tree nouvelArbre = new Tree() ;
                                TreeNode root = new TreeNode();
                                root.setId("racine_entite");
                                root.setText("Localités");
                                String[] usObjRoot = { "Localités"};
                                root.setUserObject(usObjRoot);
                                nouvelArbre.setRootNode(root);
                        
                        // on la parse et on récupère les informations qui nous interessent
                        for (Iterator<String> it= data.keySet().iterator(); it.hasNext();) {
                                
                                EntiteGeographiqueObservation ent=(EntiteGeographiqueObservation) data.get(it.next());
                                
                                id_location=ent.getIdLocation();
                                id_location = id_location.replaceAll("\"", "");
                                id_location = id_location.replace('\\',' ');
                                id_location = id_location.trim();
                                location=ent.getLocation();
                                lieuDit=ent.getLieuDit();
                                
                                if(id_location.contains("000null") || id_location.equals(null) || (id_location.trim()).equals("")) {
                                        id_location="Inconnue" ;
                                }
                                
                                if(location.contains("000null") || location.equals(null) || (location.trim().equals(""))) {
                                        location="Inconnue" ;
                                }
                                
                                if(lieuDit.contains("000null") || lieuDit.equals(null) || (lieuDit.trim().equals(""))) {
                                        lieuDit="Inconnue" ;
                                }
                                
                                Node noeudMemeId = nouvelArbre.getNodeById(""+id_location);
                                
                                // si la région existe déjà
                                        if(noeudMemeId != null)
                                        {
                                                // on teste si la localité existe
                                                Node noeudMemeLoc = nouvelArbre.getNodeById(""+(id_location+location));
                                                if(noeudMemeLoc != null)
                                                {
                                                        // enfin on teste si le lieu dit existe
                                                        Node noeudMemeLieu = nouvelArbre.getNodeById(""+(id_location+location+lieuDit));
                                                        if(noeudMemeLieu != null)
                                                        {
                                                                // tous les noeuds existent déjà, normalement ça ne devrait pas arriver
                                                        }
                                                        else
                                                        {
                                                                // enfin on ne crée que le noeud du lieu dit
                                                                TreeNode node_lieu = new TreeNode();
                                                                node_lieu.setId(""+(id_location+location+lieuDit));
                                                                node_lieu.setText(lieuDit);
                                                                noeudMemeLoc.appendChild(node_lieu) ;
                                                                String[] usObj = {lieuDit,id_location+location+lieuDit};
                                                                node_lieu.setUserObject(usObj);
                                                        }
                                                }
                                                else
                                                {
                                                        TreeNode node_loc = new TreeNode();
                                                        node_loc.setId(""+(id_location+location));
                                                        node_loc.setText(location);
                                                        noeudMemeId.appendChild(node_loc) ;
                                                        String[] usObj = {location,id_location+location};
                                                        node_loc.setUserObject(usObj);
                                                        
                                                        TreeNode node_lieu = new TreeNode();
                                                        node_lieu.setId(""+(id_location+location+lieuDit));
                                                        node_lieu.setText(lieuDit);
                                                        node_loc.appendChild(node_lieu) ;
                                                        String[] usObj2 = {lieuDit,id_location+location+lieuDit};
                                                        node_lieu.setUserObject(usObj2);
                                                        
                                                }
                                        }
                                        else
                                        {
                                                TreeNode node_id_loc = new TreeNode();
                                                node_id_loc.setId(""+id_location);
                                                node_id_loc.setText(id_location);
                                                root.appendChild(node_id_loc) ;
                                                String[] usObj = {id_location,id_location};
                                                node_id_loc.setUserObject(usObj);
                                                
                                                TreeNode node_loc = new TreeNode();
                                                node_loc.setId(""+(id_location+location));
                                                node_loc.setText(location);
                                                node_id_loc.appendChild(node_loc) ;
                                                String[] usObj2 = {location,id_location+location};
                                                node_loc.setUserObject(usObj2);
                                                
                                                TreeNode node_lieu = new TreeNode();
                                                node_lieu.setId(""+(id_location+location+lieuDit));
                                                node_lieu.setText(lieuDit);
                                                node_loc.appendChild(node_lieu) ;
                                                String[] usObj3 = {lieuDit,id_location+location+lieuDit};
                                                node_lieu.setUserObject(usObj3);
                                        }
                                        
                                        root.sort(comparerNoeuds()) ;
                                        doLayout();

                                }
                        
                                // on vide tous les noeuds
                                arbreEntitesGeographiques.getRootNode().eachChild(new NodeTraversalCallback() {
        
                                        public boolean execute(Node node) {
        
                                                node.remove();
                                                return true;
                                        }
        
                                });
                                copierFilsNoeud(root, arbreEntitesGeographiques.getRootNode());

        
                                // si l'arbre n'était pas encore considéré comme instancié
                                if (!estInstancie) {
                                        // on signale que oui
                                        estInstancie = true;
                                }
        
                                // l'état du filtre est réinitialisé
                                filtreModifie = false;
                                
                                //show() ;
                                arbreEntitesGeographiques.doLayout();

                        }
                
                if(nouvelleDonnees instanceof Observation)
                {       
                        // si l'arbre n'est pas encore chargé, on ne tient pas compte de l'ajout
                        // l'arbre complet sera de toute façon renvoyé plus tard lors du premier chargement
                        // de l'arbre
                        if(!arbreCharge) {
                                return;
                        }
                        
                        Observation obs = (Observation)nouvelleDonnees ;
                        
                        String id_location= obs.getIdentifiantLocalite();
                        id_location = id_location.replaceAll("\"", "");
                        id_location = id_location.replace('\\',' ');
                        id_location = id_location.trim();
                        
                        String location=obs.getLocalite();
                        String lieuDit=obs.getLieudit();
                        
                        Node root = arbreEntitesGeographiques.getRootNode() ;
                        
                        if(id_location.contains("000null") || id_location.equals(null) || (id_location.trim()).equals("")) {
                                id_location="Inconnue" ;
                        }
                        
                        if(location.contains("000null") || location.equals(null) || (location.trim().equals(""))) {
                                location="Inconnue" ;
                        }
                        
                        if(lieuDit.contains("000null") || lieuDit.equals(null) || (lieuDit.trim().equals(""))) {
                                lieuDit="Inconnue" ;
                        }
                        
                        Node noeudMemeId = arbreEntitesGeographiques.getNodeById(""+id_location);
                        // si la région existe déjà
                                if(noeudMemeId != null)
                                {
                                        // on teste si la localité existe
                                        Node noeudMemeLoc = arbreEntitesGeographiques.getNodeById(""+(id_location+location));
                                        if(noeudMemeLoc != null)
                                        {
                                                // enfin on teste si le lieu dit existe
                                                Node noeudMemeLieu = arbreEntitesGeographiques.getNodeById(""+(id_location+location+lieuDit));
                                                if(noeudMemeLieu != null)
                                                {
                                                        // tous les noeuds existent déjà, normalement ça ne devrait pas arriver
                                                }
                                                else
                                                {
                                                        // enfin on ne crée que le noeud du lieu dit
                                                        TreeNode node_lieu = new TreeNode();
                                                        node_lieu.setId(""+(id_location+location+lieuDit));
                                                        node_lieu.setText(lieuDit);
                                                        String[] usObj = {lieuDit,id_location+location+lieuDit};
                                                        node_lieu.setUserObject(usObj);
                                                        noeudMemeLoc.appendChild(node_lieu) ;
                                                        
                                                        root.sort(comparerNoeuds()) ;
                                                }
                                        }
                                        else
                                        {
                                                TreeNode node_loc = new TreeNode();
                                                node_loc.setId(""+(id_location+location));
                                                node_loc.setText(location);
                                                String[] usObj = {location,id_location+location};
                                                node_loc.setUserObject(usObj);
                                                noeudMemeId.appendChild(node_loc) ;
                                                
                                                TreeNode node_lieu = new TreeNode();
                                                node_lieu.setId(""+(id_location+location+lieuDit));
                                                node_lieu.setText(lieuDit);
                                                String[] usObj2 = {lieuDit,id_location+location+lieuDit};
                                                node_lieu.setUserObject(usObj2);
                                                node_loc.appendChild(node_lieu) ;
                                                
                                                root.sort(comparerNoeuds()) ;
                                                
                                        }
                        }
                        else
                        {
                                // TODO: Pourquoi l'ajout ne marche que sur la racine ?
                                
                                TreeNode node_id_loc = new TreeNode();
                                node_id_loc.setId(""+id_location);
                                node_id_loc.setText(id_location);
                                String[] usObj = {id_location,id_location};
                                node_id_loc.setUserObject(usObj);
                                root.appendChild(node_id_loc) ;
                                
                                TreeNode node_loc = new TreeNode();
                                node_loc.setId(""+(id_location+location));
                                node_loc.setText(location);
                                String[] usObj2 = {location,id_location+location};
                                node_loc.setUserObject(usObj2);
                                node_id_loc.appendChild(node_loc) ;
                                
                                TreeNode node_lieu = new TreeNode();
                                node_lieu.setId(""+(id_location+location+lieuDit));
                                node_lieu.setText(lieuDit);
                                String[] usObj3 = {lieuDit,id_location+location+lieuDit};
                                node_lieu.setUserObject(usObj3);
                                node_loc.appendChild(node_lieu) ;
                                
                                root.sort(comparerNoeuds()) ;
                                
                        }       
                                arbreEntitesGeographiques.doLayout() ;
                }
        }


        /**
         * Accesseur pour le panneau contenant l'arbre
         * 
         * @return le panneau de l'arbre des mots clés
         */
        public TreePanel getArbreMotsCles() {
                return arbreEntitesGeographiques;
        }

        /**
         * Méthode héritée de Filtrable renvoie le nom du filtre
         */
        public String renvoyerNomFiltre() {

                return "Localités";
        }

        /**
         * Renvoie un tableau contenant le nom du champ à filtrer et la valeur
         * 
         * @return un tableau contenant le nom du champ à filtrer et sa valeur
         */
        public String[] renvoyerValeursAFiltrer() {

                valider();
                
                String valeursFiltrees[] = {nomFiltre, entitesGeographiquesEncours } ;

                return valeursFiltrees;
        }

        /**
         * Fonction récursive qui prend deux noeuds d'arbre en paramètre et crée un
         * copie du sous arbre du premier noeud, qu'elle concatène au deuxième
         * 
         * @param ndPereOriginal
         *            le père des noeuds de l'arbre original
         * @param ndPereCopie
         *            le père qui va recevoir les copies
         */
        private void copierFilsNoeud(Node ndPereOriginal, TreeNode ndPereCopie) {
                if (ndPereCopie != null && ndPereOriginal != null) {
                        Node[] ndNodeFils = ndPereOriginal.getChildNodes();

                        for (int i = 0; i < ndNodeFils.length; i++) {

                                String[] usObj = (String[]) ndNodeFils[i].getUserObject();
                                TreeNode child = new TreeNode(usObj[0]);
                                child.setUserObject(usObj);
                                child.setId(""+usObj[1]);
                                ndPereCopie.appendChild(child);

                                if (!ndNodeFils[i].isLeaf()) {
                                        copierFilsNoeud(ndNodeFils[i], child);
                                }

                        }
                }
        }

        /**
         * Méthode héritée de Filtrable Renvoie l'état du filtre (modifié ou non)
         */
        public boolean renvoyerEtatFiltre() {

                return filtreModifie;
        }

        public void valider() {
                
                if (estInstancie) {
                        
                }
        }
        
        public Comparator<TreeNode> comparerNoeuds()
        {
                return new Comparator<TreeNode>() {

                        public int compare(TreeNode o1, TreeNode o2) {
                                
                                if(o1.getText().equals("Inconnue")) {
                                        return -1 ;
                                }
                                
                                if(o2.getText().equals("Inconnue")) {
                                        return 1 ;
                                }
                                
                                if(o1.getDepth() == 1 && o2.getDepth() == 1)
                                {
                                        String l1 = o1.getText() ;
                                        String l2 = o2.getText() ;
                                        if(l1.length() == 1) {
                                                l1 = "0"+l1;
                                        }
                                        
                                        if(l2.length() == 1) {
                                                l2 = "0"+l2;
                                        }
                                        
                                        Integer n1 = 0;
                                        Integer n2 = 0;
                                        
                                        try{
                                                n1 = Integer.parseInt(l1) ;
                                                n2 = Integer.parseInt(l2) ;
                                        } catch(NumberFormatException ne)  {
                                                n1 = 0;
                                                n2 = 0;
                                        }
                                        
                                        return n1.compareTo(n2) ;
                                }
                                else
                                {       
                                        String n1 = o1.getText() ;
                                        String n2 = o2.getText() ;
                                
                                        return n1.compareTo(n2) ;
                                }
                        }
                } ;
        }

        public void raz() {
                        
                arbreCharge = false ;
                arbreEntitesGeographiques.collapseAll();
                arbreEntitesGeographiques.clear() ;
                
                // on crée une racine pour l'arbre
                TreeNode root = new TreeNode("Localités");
                root.setId("racine_entite");
                String[] usObject = { "Localités" };
                root.setUserObject(usObject);

                arbreEntitesGeographiques.setRootNode(root);
                
                arbreEntitesGeographiques.getRootNode().addListener(new TreeNodeListenerAdapter() {
                        
                        public void onExpand(Node node) {
                                if(!arbreCharge)
                                {
                                        observationMediateur.obtenirDatesObservation() ;
                                        arbreCharge = true ;
                                }
                        }
                        
                }) ;
                
                arbreCharge = false ;
                
                this.doLayout() ;
                
        }
        
}