/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jfrmPrincipal.java
 *
 * Created on 15-nov-2011, 16:34:51
 */


package vista;

import java.awt.event.MouseEvent;
import java.util.Observer;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.UIManager;
import modelo.*;
import java.io.File;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import modelo.DocumentoReq;
import java.util.Observable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author acc_local
 */
public class jfrmPrincipal extends javax.swing.JFrame implements Observer{
    private DocumentoReq docPpal=new DocumentoReq();
    CasodeUso c=new CasodeUso();
    PasoCU p=new PasoCU();
    Organizacion o=new Organizacion();
    boolean nueva_version = true;
    Document document = null;
    Result result = null;
    Element raiz = null;
    
    /** Creates new form jfrmPrincipal */
    public jfrmPrincipal() {
        initComponents();
        // Look and Feel del SO en el que nos encontremos
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("Error de Look and Feel");
        }
        jtxpDocumento.setContentType("text/html");
        jtxpDocumento.setText("<center>Herramienta de Gestión de Requisitos</center>");
    }

    private void imprimirNodos(DefaultMutableTreeNode root) {
        if(nueva_version==true) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            try{
            DocumentBuilder builder = factory.newDocumentBuilder();
            DOMImplementation implementation = builder.getDOMImplementation();
            document = implementation.createDocument(null, "xml", null);
            raiz = document.createElement("Documento"); // creamos el elemento raiz
            document.setXmlVersion("1.0"); // asignamos la version de nuestro XML
            document.getDocumentElement().appendChild(raiz); //pegamos la raiz al documento
            result = new StreamResult(new java.io.File("resultado.xml"));
            }catch(Exception e){
                System.err.println("Error: "+e);
            } 
            nueva_version=false;
        }

        if(root.getChildCount()>0){
            for(Enumeration e=root.children(); e.hasMoreElements();){
                TreeNode node=(TreeNode) e.nextElement();
                
                String identificador = node.toString();
                int inicio = identificador.indexOf("-");
                int fin = identificador.indexOf(" ");
                String id=identificador.substring(inicio +1, fin);
                
                if (identificador.startsWith("[CDU]")) {
                    docPpal.CasodeUsotoXML(docPpal.BuscarCU(id), result, document, raiz);
                    try {
                    String res = transformar(identificador);
                    }
                    catch (Exception ex) {
                    Logger.getLogger(jfrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else if (identificador.startsWith("[REU]")) {
                    //docPpal.ReuniontoXML(docPpal.BuscarREU(id), result, document, raiz);
                    try {
                    String res = transformar(identificador);
                    }
                    catch (Exception ex) {
                    Logger.getLogger(jfrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else if (identificador.startsWith("[ORG]")) {
                    //docPpal.OrganizaciontoXML(docPpal.BuscarORG(id), result, document, raiz);
                    try {
                    String res = transformar(identificador);
                    }
                    catch (Exception ex) {
                    Logger.getLogger(jfrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else if (identificador.startsWith("[PAS]")) {
                    docPpal.PasotoXML(docPpal.BuscarPAS(id), result, document, raiz);
                    try {
                    String res = transformar(identificador);
                    }
                    catch (Exception ex) {
                    Logger.getLogger(jfrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else if (identificador.startsWith("[PAR]")) {
                    //docPpal.ParticipantetoXML(docPpal.BuscarPAR(id), result, document, raiz);
                    try {
                    String res = transformar(identificador);
                    }
                    catch (Exception ex) {
                    Logger.getLogger(jfrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else if (identificador.startsWith("[OBJ]")) {
                    //docPpal.ObjetivotoXML(docPpal.BuscarOBJ(id), result, document, raiz);
                    try {
                    String res = transformar(identificador);
                    }
                    catch (Exception ex) {
                    Logger.getLogger(jfrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                imprimirNodos((DefaultMutableTreeNode) node);
            }
        }
    }
    
    public String transformar(String id) throws Exception {
        String xmlOrigen = "resultado.xml";
        String xslOrigen = new String();
        
        if (id.startsWith("[CDU]")) {
            xslOrigen = "src/modelo/XMLDocCasodeUso.xsl";
        }
        else if (id.startsWith("[REU]")) {
            xslOrigen = "src/modelo/XMLDocReunion.xsl";
        }
        else if (id.startsWith("[ORG]")) {
            xslOrigen = "src/modelo/XMLDocOrganizacion.xsl";
        }
        else if (id.startsWith("[PAS]")) {
            xslOrigen = "src/modelo/XMLDocPaso.xsl";
        }
        else if (id.startsWith("[PAR]")) {
            xslOrigen = "src/modelo/XMLDocParticipante.xsl";
        }
        else if (id.startsWith("[OBJ]")) {
            xslOrigen = "src/modelo/XMLDocObjetivo.xsl";
        }
        Source xmlSource = new StreamSource(new File(xmlOrigen));
        Source xsltSource = new StreamSource(new File(xslOrigen));
        StringWriter cadenaSalida = new StringWriter();
        
        Result bufferResultado = new StreamResult(cadenaSalida);
        TransformerFactory factoriaTrans = TransformerFactory.newInstance();
        Transformer transformador = factoriaTrans.newTransformer(xsltSource);
        transformador.transform(xmlSource, bufferResultado);
        
        
        jtxpDocumento.setText(cadenaSalida.toString());
        
        //Guardar html en fichero físico
        return cadenaSalida.toString();
    }
    
    
    
    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtreDocumento = new javax.swing.JTree();
        jlblMensaje = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        jbtnNuevoElementoGlosario = new javax.swing.JButton();
        jbtnNuevaImagen = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        jbtnAñadirParticipante = new javax.swing.JButton();
        jbtnNuevaOrg = new javax.swing.JButton();
        jbtnNuevaReunion = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jbtnNuevoObjetivo = new javax.swing.JButton();
        jbtnNuevoCU = new javax.swing.JButton();
        jbtnAñadirPaso = new javax.swing.JButton();
        jbtnAñadirExcepcion = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jbtnrReqFuncional = new javax.swing.JButton();
        jbtnReq_NoFuncional = new javax.swing.JButton();
        jbtnReq_Informacion = new javax.swing.JButton();
        jbtnReq_Restriccion = new javax.swing.JButton();
        jSeparator4 = new javax.swing.JSeparator();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtxpDocumento = new javax.swing.JTextPane();
        jmnuBarraPpal = new javax.swing.JMenuBar();
        jmnuProyecto = new javax.swing.JMenu();
        jmniNuevo = new javax.swing.JMenuItem();
        jmniAbrir = new javax.swing.JMenuItem();
        jmniGuardar = new javax.swing.JMenuItem();
        jmnuSalir = new javax.swing.JMenu();
        jmniSalir = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("HGRequisitos - Universidad de Huelva");

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("[DOC] Documento ER");
        jtreDocumento.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jtreDocumento.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jtreDocumentoMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jtreDocumento);

        jToolBar1.setRollover(true);

        jbtnNuevoElementoGlosario.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nuevo_elemento_glosario.png"))); // NOI18N
        jbtnNuevoElementoGlosario.setToolTipText("Nuevo Elemento del Glosario");
        jbtnNuevoElementoGlosario.setFocusable(false);
        jbtnNuevoElementoGlosario.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnNuevoElementoGlosario.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtnNuevoElementoGlosario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevoElementoGlosarioActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnNuevoElementoGlosario);

        jbtnNuevaImagen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nueva_imagen.png"))); // NOI18N
        jbtnNuevaImagen.setToolTipText("Nueva Imagen");
        jbtnNuevaImagen.setFocusable(false);
        jbtnNuevaImagen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnNuevaImagen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jbtnNuevaImagen);
        jToolBar1.add(jSeparator3);

        jbtnAñadirParticipante.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nuevo_actor.png"))); // NOI18N
        jbtnAñadirParticipante.setToolTipText("Nuevo Participante");
        jbtnAñadirParticipante.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAñadirParticipanteActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnAñadirParticipante);

        jbtnNuevaOrg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nueva_organizacion.png"))); // NOI18N
        jbtnNuevaOrg.setToolTipText("Nueva Organización");
        jbtnNuevaOrg.setFocusable(false);
        jbtnNuevaOrg.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnNuevaOrg.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtnNuevaOrg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevaOrgActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnNuevaOrg);

        jbtnNuevaReunion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nueva_reunion.png"))); // NOI18N
        jbtnNuevaReunion.setToolTipText("Nueva Reunión");
        jbtnNuevaReunion.setFocusable(false);
        jbtnNuevaReunion.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnNuevaReunion.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtnNuevaReunion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevaReunionActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnNuevaReunion);
        jToolBar1.add(jSeparator1);

        jbtnNuevoObjetivo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nueva_objetivo.png"))); // NOI18N
        jbtnNuevoObjetivo.setToolTipText("Nuevo Objetivo");
        jbtnNuevoObjetivo.setFocusable(false);
        jbtnNuevoObjetivo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnNuevoObjetivo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtnNuevoObjetivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevoObjetivoActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnNuevoObjetivo);

        jbtnNuevoCU.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nueva_cu.png"))); // NOI18N
        jbtnNuevoCU.setToolTipText("Nuevo Caso de Uso");
        jbtnNuevoCU.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevoCUActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnNuevoCU);

        jbtnAñadirPaso.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nuevo_paso.png"))); // NOI18N
        jbtnAñadirPaso.setToolTipText("Nuevo Paso");
        jbtnAñadirPaso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAñadirPasoActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnAñadirPaso);

        jbtnAñadirExcepcion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/nueva_excepcion.png"))); // NOI18N
        jbtnAñadirExcepcion.setToolTipText("Nueva Excepcion");
        jbtnAñadirExcepcion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAñadirExcepcionActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnAñadirExcepcion);
        jToolBar1.add(jSeparator2);

        jbtnrReqFuncional.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/req_funcional.png"))); // NOI18N
        jbtnrReqFuncional.setToolTipText("Nuevo Requisito Funcional");
        jbtnrReqFuncional.setFocusable(false);
        jbtnrReqFuncional.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnrReqFuncional.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtnrReqFuncional.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnrReqFuncionalActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnrReqFuncional);

        jbtnReq_NoFuncional.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/req_nofuncional.png"))); // NOI18N
        jbtnReq_NoFuncional.setToolTipText("Nuevo Requisito No Funcional");
        jbtnReq_NoFuncional.setFocusable(false);
        jbtnReq_NoFuncional.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnReq_NoFuncional.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtnReq_NoFuncional.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnReq_NoFuncionalActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnReq_NoFuncional);

        jbtnReq_Informacion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/req_informacion.png"))); // NOI18N
        jbtnReq_Informacion.setToolTipText("Nuevo Requisito de Información");
        jbtnReq_Informacion.setFocusable(false);
        jbtnReq_Informacion.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnReq_Informacion.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtnReq_Informacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnReq_InformacionActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnReq_Informacion);

        jbtnReq_Restriccion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vista/iconos/req_restriccion.png"))); // NOI18N
        jbtnReq_Restriccion.setToolTipText("Nuevo Requisito de Restricción");
        jbtnReq_Restriccion.setFocusable(false);
        jbtnReq_Restriccion.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtnReq_Restriccion.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtnReq_Restriccion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnReq_RestriccionActionPerformed(evt);
            }
        });
        jToolBar1.add(jbtnReq_Restriccion);

        jScrollPane2.setViewportView(jtxpDocumento);

        jmnuProyecto.setText("Proyecto");

        jmniNuevo.setText("Nuevo");
        jmnuProyecto.add(jmniNuevo);

        jmniAbrir.setText("Abrir");
        jmnuProyecto.add(jmniAbrir);

        jmniGuardar.setText("Guardar");
        jmnuProyecto.add(jmniGuardar);

        jmnuBarraPpal.add(jmnuProyecto);

        jmnuSalir.setText("Salir");

        jmniSalir.setText("Salir");
        jmniSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmniSalirActionPerformed(evt);
            }
        });
        jmnuSalir.add(jmniSalir);

        jmnuBarraPpal.add(jmnuSalir);

        setJMenuBar(jmnuBarraPpal);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 833, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlblMensaje, javax.swing.GroupLayout.DEFAULT_SIZE, 813, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator4, javax.swing.GroupLayout.DEFAULT_SIZE, 813, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlblMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
 
    
    
    
    private void jmniSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmniSalirActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jmniSalirActionPerformed
    
    
    private void jbtnAñadirParticipanteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAñadirParticipanteActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();

        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[ORG]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una organización [ORG]");
            }
            else {
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;

                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmParticipante jfParticipante=new jfrmParticipante(this, o, insertNode, insertIndex, getDocPpal());
                jfParticipante.setLocationRelativeTo(null);
                jfParticipante.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }
}//GEN-LAST:event_jbtnAñadirParticipanteActionPerformed

    private void jbtnNuevoCUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevoCUActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();
        
        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[DOC]") || nombre_aux.startsWith("[SEC]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una sección [SEC] o un documento [DOC]");
            } 
            else {  
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;
                
                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }
                
                jfrmCasodeUso jfCasodeUso=new jfrmCasodeUso(this, getDocPpal(), insertNode, insertIndex);
                
                jfCasodeUso.setLocationRelativeTo(null);
                jfCasodeUso.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }
    }//GEN-LAST:event_jbtnNuevoCUActionPerformed

    private void jbtnAñadirPasoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAñadirPasoActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();
        
        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!nombre_aux.startsWith("[CDU]")) {
                jlblMensaje.setText("Error: No se ha seleccionado un caso de uso [CDU]");
            } 
            else {  
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;
                
                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmPaso jfPaso=new jfrmPaso(this, c, insertNode, insertIndex, getDocPpal());
                jfPaso.setLocationRelativeTo(null);
                jfPaso.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }
    }//GEN-LAST:event_jbtnAñadirPasoActionPerformed

    private void jbtnAñadirExcepcionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAñadirExcepcionActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();
        
        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!nombre_aux.startsWith("[PAS]")) {
                jlblMensaje.setText("Error: No se ha seleccionado un paso [PAS]");
            } 
            else {  
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;
                
                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmExcepcion jfExcepcion=new jfrmExcepcion(this, p, insertNode, insertIndex);
                jfExcepcion.setLocationRelativeTo(null);
                jfExcepcion.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }
    }//GEN-LAST:event_jbtnAñadirExcepcionActionPerformed

    private void jbtnNuevaOrgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevaOrgActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();

        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[DOC]") || nombre_aux.startsWith("[SEC]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una sección [SEC] o un documento [DOC]");
            }
            else {
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;

                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmOrganizacion jfOrganizacion=new jfrmOrganizacion(this, getDocPpal(), insertNode, insertIndex);
                jfOrganizacion.setLocationRelativeTo(null);
                jfOrganizacion.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }
    }//GEN-LAST:event_jbtnNuevaOrgActionPerformed

    private void jbtnReq_RestriccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnReq_RestriccionActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();
        
        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[DOC]") || nombre_aux.startsWith("[SEC]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una sección [SEC] o un documento [DOC]");
            }
            else {
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;

                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmReqRestriccion jfRestriccion=new jfrmReqRestriccion(this, getDocPpal(), insertNode, insertIndex);
                jfRestriccion.setLocationRelativeTo(null);
                jfRestriccion.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }    
    }//GEN-LAST:event_jbtnReq_RestriccionActionPerformed

private void jbtnNuevoElementoGlosarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevoElementoGlosarioActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();
        if(tp==null){
            jlblMensaje.setText("Seleccione un nodo antes");
        } 
        else {
            MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;
                
                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }
                
            jfrmNuevoElemento jele = new jfrmNuevoElemento(this, insertNode, insertIndex);
            jele.setLocationRelativeTo(null);
            jele.setVisible(true);
            this.setEnabled(false);

        }
}//GEN-LAST:event_jbtnNuevoElementoGlosarioActionPerformed

    private void jbtnrReqFuncionalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnrReqFuncionalActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();

        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[DOC]") || nombre_aux.startsWith("[SEC]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una sección [SEC] o un documento [DOC]");
            }
            else {
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;

                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmReqFuncional jfFuncional=new jfrmReqFuncional(this, getDocPpal(), insertNode, insertIndex);
                jfFuncional.setLocationRelativeTo(null);
                jfFuncional.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }         
    }//GEN-LAST:event_jbtnrReqFuncionalActionPerformed

    private void jbtnReq_InformacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnReq_InformacionActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();
        
        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[DOC]") || nombre_aux.startsWith("[SEC]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una sección [SEC] o un documento [DOC]");
            }
            else {
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;

                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmReqInformacion jfInformacion=new jfrmReqInformacion(this, getDocPpal(), insertNode, insertIndex);
                jfInformacion.setLocationRelativeTo(null);
                jfInformacion.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        } 
    }//GEN-LAST:event_jbtnReq_InformacionActionPerformed

    private void jbtnReq_NoFuncionalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnReq_NoFuncionalActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();

        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[DOC]") || nombre_aux.startsWith("[SEC]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una sección [SEC] o un documento [DOC]");
            }
            else {
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;

                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmReqNoFuncional jfNoFuncional=new jfrmReqNoFuncional(this, getDocPpal(), insertNode, insertIndex);
                jfNoFuncional.setLocationRelativeTo(null);
                jfNoFuncional.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }
    }//GEN-LAST:event_jbtnReq_NoFuncionalActionPerformed

    private void jtreDocumentoMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtreDocumentoMouseReleased
        if (evt.isPopupTrigger()) myPopupEvent(evt);
    }//GEN-LAST:event_jtreDocumentoMouseReleased

    private void jbtnNuevaReunionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevaReunionActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();

        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[DOC]") || nombre_aux.startsWith("[SEC]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una sección [SEC] o un documento [DOC]");
            }
            else {
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;

                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmReunion jfReunion=new jfrmReunion(this, getDocPpal(), insertNode, insertIndex);
                jfReunion.setLocationRelativeTo(null);
                jfReunion.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }
    }//GEN-LAST:event_jbtnNuevaReunionActionPerformed

    private void jbtnNuevoObjetivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevoObjetivoActionPerformed
        TreePath tp = getJtreDocumento().getSelectionPath();

        if(tp!=null) {
            DefaultMutableTreeNode nodo_aux = (DefaultMutableTreeNode) tp.getLastPathComponent();
            String nombre_aux = (String) nodo_aux.getUserObject();
            if(!(nombre_aux.startsWith("[DOC]") || nombre_aux.startsWith("[SEC]"))) {
                jlblMensaje.setText("Error: No se ha seleccionado una sección [SEC] o un documento [DOC]");
            }
            else {
                MutableTreeNode insertNode= (MutableTreeNode) tp.getLastPathComponent();
                int insertIndex=0;

                if(insertNode.getChildCount()!=0) {
                    insertIndex=insertNode.getChildCount();
                }

                jfrmObjetivo jfObjetivo=new jfrmObjetivo(this, getDocPpal(), insertNode, insertIndex);
                jfObjetivo.setLocationRelativeTo(null);
                jfObjetivo.setVisible(true);
                this.setEnabled(false);
            }
        }
        else {
            jlblMensaje.setText("Error: Ningun nodo seleccionado");
        }
    }//GEN-LAST:event_jbtnNuevoObjetivoActionPerformed
    
    private void myPopupEvent(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            JTree tree = (JTree)e.getSource();
            TreePath path = tree.getPathForLocation(x, y);
            if (path != null) { 
                tree.setSelectionPath(path);
                String label = "Editar" ;
                String label2 = "Elimnar";
                JPopupMenu popup = new JPopupMenu();
                popup.add(new JMenuItem(label));
                popup.add(new JMenuItem(label2));
                popup.show(tree, x, y);
            }
    }
    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        jfrmPrincipal principal = new jfrmPrincipal();
        principal.getDocPpal().addObserver(principal);
        principal.setLocationRelativeTo(null);
        principal.setVisible(true);
        
        
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new jfrmPrincipal().setVisible(true);
//                
//            }
//        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton jbtnAñadirExcepcion;
    private javax.swing.JButton jbtnAñadirParticipante;
    private javax.swing.JButton jbtnAñadirPaso;
    private javax.swing.JButton jbtnNuevaImagen;
    private javax.swing.JButton jbtnNuevaOrg;
    private javax.swing.JButton jbtnNuevaReunion;
    private javax.swing.JButton jbtnNuevoCU;
    private javax.swing.JButton jbtnNuevoElementoGlosario;
    private javax.swing.JButton jbtnNuevoObjetivo;
    private javax.swing.JButton jbtnReq_Informacion;
    private javax.swing.JButton jbtnReq_NoFuncional;
    private javax.swing.JButton jbtnReq_Restriccion;
    private javax.swing.JButton jbtnrReqFuncional;
    private javax.swing.JLabel jlblMensaje;
    private javax.swing.JMenuItem jmniAbrir;
    private javax.swing.JMenuItem jmniGuardar;
    private javax.swing.JMenuItem jmniNuevo;
    private javax.swing.JMenuItem jmniSalir;
    private javax.swing.JMenuBar jmnuBarraPpal;
    private javax.swing.JMenu jmnuProyecto;
    private javax.swing.JMenu jmnuSalir;
    private javax.swing.JTree jtreDocumento;
    private javax.swing.JTextPane jtxpDocumento;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the jtreDocumento
     */
    public javax.swing.JTree getJtreDocumento() {
        return jtreDocumento;
    }

    /**
     * @param jtreDocumento the jtreDocumento to set
     */
    public void setJtreDocumento(javax.swing.JTree jtreDocumento) {
        this.jtreDocumento = jtreDocumento;
    }

    protected void mostrarMensaje(String mensaje) {
                JOptionPane.showMessageDialog(this, mensaje, "Advertencia",
                                JOptionPane.WARNING_MESSAGE);
    }
    
    //Se encarga de actualizar la informacion del TextPanel cuando se añade un nuevo nodo
    //o se modifica uno de los anteriores (Por hacer lo segundo).
    public void update(Observable o, Object arg) {
        DefaultTreeModel model=(DefaultTreeModel) this.getJtreDocumento().getModel();
        DefaultMutableTreeNode root=(DefaultMutableTreeNode) model.getRoot();
        imprimirNodos(root);
        nueva_version=true;
    }

    /**
     * @return the docPpal
     */
    public DocumentoReq getDocPpal() {
        return docPpal;
    }

}
