/*
 *      Luis Israel Diéguez Arjona
 *      Sonia Cejas Soria
 *      Sergio Cabello García
 *      María José González Cordero
 *
 *      Ingeniería del Software de Gestión II
 *      Ingeniería Técnica Informática de Gestión
 *      Universidad de Huelva
 */

package vista;

import controlador.Utilidades;
import java.awt.Color;
import java.util.*;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import modelo.*;





public class jfSeccion_Apendice extends javax.swing.JFrame implements Observer {
    // Formulario padre
    jfHome home;
    boolean modificadoSeccion = false;
    boolean modificadoApendice = false;
    String idSeccion;
    String idApendice;
    // Colores
    Color colorBlanco = new Color(255, 255, 255);
    Color colorAmarillo = new Color(255, 255, 102);
    // Fecha
    Date fecha;
    // Utilidades
    Utilidades utilidades = new Utilidades();
    // JTree
    MutableTreeNode currentNode;
    MutableTreeNode insertNode;
    int insertIndex;
    // Control del Update de Observers
    int contadorEjecuciones = 0;
    String ident;
    private String numeracion = "";


    public jfSeccion_Apendice() {
        initComponents();
        this.buttonGroup.add(jRadioButton_seccion);
        this.buttonGroup.add(jRadioButton_apendice);
        jRadioButton_seccion.setSelected(true);
    }
    public jfSeccion_Apendice(jfHome home) {
        // Inicializo
        initComponents();
        this.buttonGroup.add(jRadioButton_seccion);
        this.buttonGroup.add(jRadioButton_apendice);
        jRadioButton_seccion.setSelected(true);
        this.home = home;
        this.insertNode = home.getInsertNode();
        this.insertIndex = home.getInsertIndex(insertNode);
        
        // Configura el identificador
        ident = this.home.documentoRequisitos.getNuevoIdentificadorSeccion();
        this.jTextField_identificacion.setText(ident);
        
        // Fecha del sistema
        fecha = new Date();
        jDateChooserFecha.setDate(fecha);
        
        
        //Saber que elemento estaba seleccionado en home.
        TreePath tp = home.getJTree().getSelectionPath();  
        
        //MutableTreeNode nodoSeleccionado = (MutableTreeNode) tp.getLastPathComponent();
        TreeNode nodoSeleccionado = (TreeNode) tp.getLastPathComponent();
        TreeNode raiz = (TreeNode)home.getJTree().getModel().getRoot();
        
        int numHijos = this.utilidades.getHijosTipoSeccion(nodoSeleccionado);

        //this.utilidades.getPreIdentificadorNodo(raiz);
        
        
        String preIdent = utilidades.getPreIdentificadorNodo (nodoSeleccionado); 
        if (preIdent.equals("SEC")) {
            String identPadre = utilidades.getIdentificadorNodo((MutableTreeNode)nodoSeleccionado);
            //Buscar la seccion que tenga ese identificador.
            ArrayList<Seccion> seccion = home.documentoRequisitos.getSeccion();
            Boolean encontrado = false;
            int i = 0;
            while (!encontrado && i < seccion.size()) {
                if (seccion.get(i).getIdentificacion().equals(identPadre)) {
                    numeracion = seccion.get(i).getNumeracion() + numHijos + ".";
                    
                    encontrado = true;
                }
                i++;
            }
        }
        else{            
            numeracion = numHijos + ".";
        }
            
    }
            

    

    public void inicializarModificacionSeccion (Seccion seccion) {
        modificadoSeccion = true;
        idSeccion = "SEC-" + utilidades.getIdentificadorNumerico(seccion.getIdentificacion());
        // Pestaña General
        jLabel_identificador.setText("SEC-");
        jRadioButton_seccion.setSelected(true);
        jRadioButton_seccion.setEnabled(false);
        jRadioButton_apendice.setEnabled(false);
        jTextField_identificacion.setText(utilidades.getIdentificadorNumerico(seccion.getIdentificacion()));
        jTextField_nombre.setText(seccion.getNombre());
        jTextField_nombre.setEditable(false);
        String version = seccion.getVersion();
        if (!version.equals(".")) {
            String versIzq = version.substring(0, version.indexOf("."));
            String versDer = version.substring(version.indexOf(".")+1, version.length());
            jTextField_versionIzq.setText(versIzq);
            jTextField_versionDer.setText(versDer);
        }
        jDateChooserFecha.setDate(seccion.getFecha());

        // Pestaña Detalle

        // Pestaña Comentarios
        jTextArea_comentarios.setText(seccion.getComentario());
    }


    public void inicializarModificacionApendice (Apendice apendice) {
        modificadoApendice = true;
        idApendice = "APE-" + utilidades.getIdentificadorNumerico(apendice.getIdentificacion());
        // Pestaña General
        jLabel_identificador.setText("APE-");
        jRadioButton_apendice.setSelected(true);
        jRadioButton_seccion.setEnabled(false);
        jRadioButton_apendice.setEnabled(false);
        jTextField_identificacion.setText(utilidades.getIdentificadorNumerico(apendice.getIdentificacion()));
        jTextField_nombre.setText(apendice.getNombre());
        String version = apendice.getVersion();
        if (!version.equals(".")) {
            String versIzq = version.substring(0, version.indexOf("."));
            String versDer = version.substring(version.indexOf(".")+1, version.length());
            jTextField_versionIzq.setText(versIzq);
            jTextField_versionDer.setText(versDer);
        }
        jDateChooserFecha.setDate(apendice.getFecha());

        // Pestaña Detalle
        if(apendice.getOrdenar()){
            jCheckBox_ordenar.setSelected(true);
        }
        // Pestaña Comentarios
        jTextArea_comentarios.setText(apendice.getComentario());
    }



    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jLabel_identificador = new javax.swing.JLabel();
        jTextField_identificacion = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField_nombre = new javax.swing.JTextField();
        jPanel9 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField_versionIzq = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField_versionDer = new javax.swing.JTextField();
        jDateChooserFecha = new com.toedter.calendar.JDateChooser();
        jPanel10 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList_autores = new javax.swing.JList();
        jButton_anadirAutor = new javax.swing.JButton();
        jButton_eliminarAutor = new javax.swing.JButton();
        jPanel11 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList_fuentes = new javax.swing.JList();
        jButton_eliminarFuente = new javax.swing.JButton();
        jButton_anadirFuente = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel14 = new javax.swing.JPanel();
        jRadioButton_seccion = new javax.swing.JRadioButton();
        jRadioButton_apendice = new javax.swing.JRadioButton();
        jPanel15 = new javax.swing.JPanel();
        jCheckBox_ordenar = new javax.swing.JCheckBox();
        jPanel7 = new javax.swing.JPanel();
        jPanel23 = new javax.swing.JPanel();
        jScrollPane6 = new javax.swing.JScrollPane();
        jTextArea_comentarios = new javax.swing.JTextArea();
        jButton_aceptar = new javax.swing.JButton();
        jButton_cancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sección/Apéndice");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jPanel1.setPreferredSize(new java.awt.Dimension(563, 306));

        jTabbedPane1.setPreferredSize(new java.awt.Dimension(564, 262));

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Identificación"));
        jPanel8.setToolTipText("");
        jPanel8.setName(""); // NOI18N

        jLabel_identificador.setText("SEC-");

        jTextField_identificacion.setEditable(false);
        jTextField_identificacion.setMinimumSize(new java.awt.Dimension(6, 15));
        jTextField_identificacion.setPreferredSize(new java.awt.Dimension(35, 20));

        jLabel2.setText("Nombre:");

        jTextField_nombre.setPreferredSize(new java.awt.Dimension(300, 20));

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel_identificador)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField_identificacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 104, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel_identificador)
                .addComponent(jTextField_identificacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2)
                .addComponent(jTextField_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Versión"));
        jPanel9.setPreferredSize(new java.awt.Dimension(525, 43));

        jLabel3.setText("Número:");

        jLabel4.setText("Fecha:");

        jTextField_versionIzq.setPreferredSize(new java.awt.Dimension(20, 20));

        jLabel5.setText(".");

        jTextField_versionDer.setPreferredSize(new java.awt.Dimension(20, 20));

        jDateChooserFecha.setDateFormatString("dd/MM/yyyy");

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField_versionIzq, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField_versionDer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(68, 68, 68)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jDateChooserFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(226, Short.MAX_VALUE))
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jTextField_versionIzq, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(jTextField_versionDer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4))
                    .addComponent(jDateChooserFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel10.setBorder(javax.swing.BorderFactory.createTitledBorder("Autores"));
        jPanel10.setPreferredSize(new java.awt.Dimension(265, 114));

        jList_autores.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Pepito (STK-0001)", "Julio (STK-0002)" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList_autores);

        jButton_anadirAutor.setText("Añadir");

        jButton_eliminarAutor.setText("Eliminar");

        javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
        jPanel10.setLayout(jPanel10Layout);
        jPanel10Layout.setHorizontalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel10Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
                    .addGroup(jPanel10Layout.createSequentialGroup()
                        .addComponent(jButton_anadirAutor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton_eliminarAutor)))
                .addContainerGap())
        );
        jPanel10Layout.setVerticalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel10Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_eliminarAutor)
                    .addComponent(jButton_anadirAutor))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder("Fuentes"));
        jPanel11.setPreferredSize(new java.awt.Dimension(265, 78));

        jList_fuentes.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Andrés (STK-0003)" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jList_fuentes);

        jButton_eliminarFuente.setText("Eliminar");

        jButton_anadirFuente.setText("Añadir");

        javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
        jPanel11.setLayout(jPanel11Layout);
        jPanel11Layout.setHorizontalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel11Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addComponent(jButton_anadirFuente)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton_eliminarFuente)))
                .addContainerGap())
        );
        jPanel11Layout.setVerticalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel11Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_eliminarFuente)
                    .addComponent(jButton_anadirFuente))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE)
                    .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                        .addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                    .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("General", jPanel2);

        jPanel14.setBorder(javax.swing.BorderFactory.createTitledBorder("Tipo de sección"));

        jRadioButton_seccion.setText("La sección es una sección normal");
        jRadioButton_seccion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton_seccionActionPerformed(evt);
            }
        });

        jRadioButton_apendice.setText("La sección es un apéndice");
        jRadioButton_apendice.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton_apendiceActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
        jPanel14.setLayout(jPanel14Layout);
        jPanel14Layout.setHorizontalGroup(
            jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel14Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jRadioButton_apendice)
                    .addComponent(jRadioButton_seccion))
                .addContainerGap(23, Short.MAX_VALUE))
        );
        jPanel14Layout.setVerticalGroup(
            jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel14Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jRadioButton_seccion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jRadioButton_apendice)
                .addContainerGap())
        );

        jPanel15.setBorder(javax.swing.BorderFactory.createTitledBorder("Orden"));

        jCheckBox_ordenar.setText("Ordenar elementos por nombre");

        javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
        jPanel15.setLayout(jPanel15Layout);
        jPanel15Layout.setHorizontalGroup(
            jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel15Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCheckBox_ordenar)
                .addContainerGap(31, Short.MAX_VALUE))
        );
        jPanel15Layout.setVerticalGroup(
            jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel15Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCheckBox_ordenar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel14, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(66, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Detalle", jPanel3);

        jPanel23.setBorder(javax.swing.BorderFactory.createTitledBorder("Comentarios"));

        jTextArea_comentarios.setColumns(20);
        jTextArea_comentarios.setLineWrap(true);
        jTextArea_comentarios.setRows(5);
        jScrollPane6.setViewportView(jTextArea_comentarios);

        javax.swing.GroupLayout jPanel23Layout = new javax.swing.GroupLayout(jPanel23);
        jPanel23.setLayout(jPanel23Layout);
        jPanel23Layout.setHorizontalGroup(
            jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel23Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 511, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel23Layout.setVerticalGroup(
            jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel23Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel23, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel23, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Comentarios", jPanel7);

        jButton_aceptar.setText("Aceptar");
        jButton_aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_aceptarActionPerformed(evt);
            }
        });

        jButton_cancelar.setText("Cancelar");
        jButton_cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_cancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(402, Short.MAX_VALUE)
                .addComponent(jButton_aceptar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton_cancelar)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_cancelar)
                    .addComponent(jButton_aceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_cancelarActionPerformed
        home.setEnabled(true);
        this.dispose();
}//GEN-LAST:event_jButton_cancelarActionPerformed
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        home.setEnabled(true);
        this.dispose();
    }//GEN-LAST:event_formWindowClosed
    private void jButton_aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_aceptarActionPerformed
        boolean puedoCerrar = true;

        if (jRadioButton_seccion.isSelected()){ //Si es Sección
            Seccion seccion = new Seccion();

            //Pestaña General

            // Identificador
            seccion.setIdentificacion(this.jLabel_identificador.getText() + this.jTextField_identificacion.getText());
            
            // Nombre
            if (!this.jTextField_nombre.getText().equals("")) {
                this.jTextField_nombre.setBackground(colorBlanco);
                seccion.setNombre(this.jTextField_nombre.getText());
            } else {
                this.jTextField_nombre.setBackground(colorAmarillo);
                puedoCerrar = false;
            }
            
            //Version
            seccion.setVersion(this.jTextField_versionIzq.getText() + "." + this.jTextField_versionDer.getText());
            
            //Insertamos la fecha.
            fecha = jDateChooserFecha.getDate();
            if(fecha == null)
                fecha = new Date(); //sino metemos ninguna fecha que se guarde la del sistema
            seccion.setFecha(fecha);
            
            // Autores
            /*if (this.jList_autores.getComponentCount() != 0) {                                                  // SI hay autores en el formulario
                ArrayList<Participante> autores = new ArrayList<Participante>();

                for (int i = 0; i < this.jList_autores.getComponentCount(); i++) {                              // Recorro cada autor del formulario
                    ArrayList<Participante> participantes = documentoRequisitos.getParticipante();              // Obtengo los participantes ya introducidos en el documento requisitos
                    Participante participante;
                    String elemento = this.jList_autores.getModel().getElementAt(i).toString();
                    // Busco el autor introducido en el formulario entre los participantes ya incluídos en el documento
                    for (int j = 0; j < participantes.size(); j++) {                                            // Recorro los partipantes del documento
                        participante = participantes.get(j);
                        int posicionInicial = elemento.indexOf("STK-");                                         // Busco inicio posición del identificador
                        String identificador = elemento.substring(posicionInicial, 8);                          // Obtengo el identificador desde el jList
                        if (participante.getIdentificacion().equals(identificador))
                            autores.add(participante);
                    }
                }
                casoUso.setAutores(autores);
            }*/

            // Fuentes
            /*if (this.jList_fuentes.getComponentCount() != 0) {                                                  // SI hay autores en el formulario
                ArrayList<Participante> fuentes = new ArrayList<Participante>();

                for (int i = 0; i < this.jList_fuentes.getComponentCount(); i++) {                              // Recorro cada fuente del formulario
                    ArrayList<Participante> participantes = documentoRequisitos.getParticipante();              // Obtengo los participantes ya introducidos en el documento requisitos
                    Participante participante;
                    String elemento = this.jList_fuentes.getModel().getElementAt(i).toString();
                    // Busco el autor introducido en el formulario entre los participantes ya incluídos en el documento
                    for (int j = 0; j < participantes.size(); j++) {                                            // Recorro los partipantes del documento
                        participante = participantes.get(j);
                        int posicionInicial = elemento.indexOf("STK-");                                         // Busco inicio posición del identificador
                        String identificador = elemento.substring(posicionInicial, 8);                          // Obtengo el identificador desde el jList
                        if (participante.getIdentificacion().equals(identificador))
                            fuentes.add(participante);
                    }
                }
                casoUso.setFuentes(fuentes);
            */
            
            //Pestaña Detalle
            seccion.setOrdenar(this.jCheckBox_ordenar.isSelected());
            seccion.setComentario(jTextArea_comentarios.getText());
            
            //Calcular la numeración.
            
            //Saber que elemento estaba seleccionado en home.
            TreePath tp = home.getJTree().getSelectionPath();  
            TreeNode nodoSeleccionado = (TreeNode) tp.getLastPathComponent();
            int numHijos = this.utilidades.getHijosTipoSeccion(nodoSeleccionado);

            String preIdent = utilidades.getPreIdentificadorNodo (nodoSeleccionado); 
            if (preIdent.equals("SEC")) {
                String identPadre = utilidades.getIdentificadorNodo((MutableTreeNode)nodoSeleccionado);
                //Buscar la seccion que tenga ese identificador.
                ArrayList<Seccion> miArrayseccion = home.documentoRequisitos.getSeccion();
                Boolean encontrado = false;
                int i = 0;
                while (!encontrado && i < miArrayseccion.size()) {
                    if (miArrayseccion.get(i).getIdentificacion().equals(identPadre)) {
                        numeracion = miArrayseccion.get(i).getNumeracion() + "." + numHijos;
                        encontrado = true;
                    }
                    i++;
                }
            }
            else if (preIdent.equals("APE")) {
                String identPadre = utilidades.getIdentificadorNodo((MutableTreeNode)nodoSeleccionado);
                //Buscar la seccion que tenga ese identificador.
                ArrayList<Apendice> miArrayApendice = home.documentoRequisitos.getApendice();
                Boolean encontrado = false;
                int i = 0;
                while (!encontrado && i < miArrayApendice.size()) {
                    if (miArrayApendice.get(i).getIdentificacion().equals(identPadre)) {
                        numeracion = miArrayApendice.get(i).getNumeracion() + "." + numHijos;
                        encontrado = true;
                    }
                    i++;
                }
            }
            else{
                numeracion = numeracion = String.valueOf(numHijos);
            }
                           
            //Numeracion de la seccion.
            seccion.setNumeracion(numeracion);
            
            // Fin de la captura de los datos desde el formulario
            if (puedoCerrar) {
                if (modificadoSeccion)
                    home.documentoRequisitos.modifySeccion(seccion);
                else
                    home.documentoRequisitos.addSeccion(seccion);

                // Actualizo el JTree
                actualizarJTreeSeccion(seccion);

                // Cierro la ventana
                home.setEnabled(true);
                this.dispose();
            }
        }
        else if (jRadioButton_apendice.isSelected()){ //Si es Apéndice
            Apendice apendice = new Apendice();
            
            // Identificador

            apendice.setIdentificacion(this.jLabel_identificador.getText() + this.jTextField_identificacion.getText());
            this.jTextField_nombre.setEditable(false);
            // Nombre
            if (!this.jTextField_nombre.getText().equals("")) {
                this.jTextField_nombre.setBackground(colorBlanco);
                apendice.setNombre(this.jTextField_nombre.getText());
            } else {
                this.jTextField_nombre.setBackground(colorAmarillo);
                puedoCerrar = false;
            }
            
            //Version
            apendice.setVersion(this.jTextField_versionIzq.getText() + "." + this.jTextField_versionDer.getText());
            
            //Insertamos la fecha.
            fecha = jDateChooserFecha.getDate();
            if(fecha == null)
                fecha = new Date(); //sino metemos ninguna fecha que se guarde la del sistema
            apendice.setFecha(fecha);
            
            // Autores
            /*if (this.jList_autores.getComponentCount() != 0) {                                                  // SI hay autores en el formulario
                ArrayList<Participante> autores = new ArrayList<Participante>();

                for (int i = 0; i < this.jList_autores.getComponentCount(); i++) {                              // Recorro cada autor del formulario
                    ArrayList<Participante> participantes = documentoRequisitos.getParticipante();              // Obtengo los participantes ya introducidos en el documento requisitos
                    Participante participante;
                    String elemento = this.jList_autores.getModel().getElementAt(i).toString();
                    // Busco el autor introducido en el formulario entre los participantes ya incluídos en el documento
                    for (int j = 0; j < participantes.size(); j++) {                                            // Recorro los partipantes del documento
                        participante = participantes.get(j);
                        int posicionInicial = elemento.indexOf("STK-");                                         // Busco inicio posición del identificador
                        String identificador = elemento.substring(posicionInicial, 8);                          // Obtengo el identificador desde el jList
                        if (participante.getIdentificacion().equals(identificador))
                            autores.add(participante);
                    }
                }
                casoUso.setAutores(autores);
            }*/

            // Fuentes
            /*if (this.jList_fuentes.getComponentCount() != 0) {                                                  // SI hay autores en el formulario
                ArrayList<Participante> fuentes = new ArrayList<Participante>();

                for (int i = 0; i < this.jList_fuentes.getComponentCount(); i++) {                              // Recorro cada fuente del formulario
                    ArrayList<Participante> participantes = documentoRequisitos.getParticipante();              // Obtengo los participantes ya introducidos en el documento requisitos
                    Participante participante;
                    String elemento = this.jList_fuentes.getModel().getElementAt(i).toString();
                    // Busco el autor introducido en el formulario entre los participantes ya incluídos en el documento
                    for (int j = 0; j < participantes.size(); j++) {                                            // Recorro los partipantes del documento
                        participante = participantes.get(j);
                        int posicionInicial = elemento.indexOf("STK-");                                         // Busco inicio posición del identificador
                        String identificador = elemento.substring(posicionInicial, 8);                          // Obtengo el identificador desde el jList
                        if (participante.getIdentificacion().equals(identificador))
                            fuentes.add(participante);
                    }
                }
                casoUso.setFuentes(fuentes);
            */
            
            //Pestaña Detalle
            apendice.setOrdenar(this.jCheckBox_ordenar.isSelected());
            
            //Pestaña Comentarios
            apendice.setComentario(this.jTextArea_comentarios.getText());

            
            //Calcular la numeración.
            
            //Saber que elemento estaba seleccionado en home.
            TreePath tp = home.getJTree().getSelectionPath();  
            TreeNode nodoSeleccionado = (TreeNode) tp.getLastPathComponent();
            int numHijos = this.utilidades.getHijosTipoApendice(nodoSeleccionado);

            String preIdent = utilidades.getPreIdentificadorNodo (nodoSeleccionado); 
            if (preIdent.equals("SEC")) {
                String identPadre = utilidades.getIdentificadorNodo((MutableTreeNode)nodoSeleccionado);
                //Buscar la seccion que tenga ese identificador.
                ArrayList<Seccion> miArrayseccion = home.documentoRequisitos.getSeccion();
                Boolean encontrado = false;
                int i = 0;
                while (!encontrado && i < miArrayseccion.size()) {
                    if (miArrayseccion.get(i).getIdentificacion().equals(identPadre)) {
                        char digit = (char) (numHijos+64);
                        numeracion = miArrayseccion.get(i).getNumeracion() + "." + digit;
                        encontrado = true;
                    }
                    i++;
                }
            }
            else if (preIdent.equals("APE")) {
                String identPadre = utilidades.getIdentificadorNodo((MutableTreeNode)nodoSeleccionado);
                //Buscar la seccion que tenga ese identificador.
                ArrayList<Apendice> miArrayApendice = home.documentoRequisitos.getApendice();
                Boolean encontrado = false;
                int i = 0;
                while (!encontrado && i < miArrayApendice.size()) {
                    if (miArrayApendice.get(i).getIdentificacion().equals(identPadre)) {
                        char digit = (char) (numHijos+64);
                        numeracion = miArrayApendice.get(i).getNumeracion() + "." + digit;
                        encontrado = true;
                    }
                    i++;
                }
            }
            else{
                numHijos +=64;
                char digit = (char) (numHijos);
                numeracion = String.valueOf(digit);
            }

            apendice.setNumeracion(numeracion);
            
            // Fin de la captura de los datos desde el formulario
            if (puedoCerrar) {
                if  (modificadoApendice == true)
                    home.documentoRequisitos.modifyApendice(apendice);
                else
                    home.documentoRequisitos.addApendice(apendice);

                // Actualizo el JTree
                actualizarJTreeApendice(apendice);

                // Cierro la ventana
                home.setEnabled(true);
                this.dispose();
            }
        }
    }//GEN-LAST:event_jButton_aceptarActionPerformed

    private void actualizarJTreeSeccion (Seccion seccion) {
        MutableTreeNode node = new DefaultMutableTreeNode(seccion.getNombre() + " (" + seccion.getIdentificacion() + ")");
        DefaultTreeModel model = (DefaultTreeModel) home.getJTree().getModel();
        if (modificadoSeccion == false)
            model.insertNodeInto(node, insertNode, insertIndex);

        // Expande el JTree
        for (int j = 0; j < home.getJTree().getSize().height; j++)
            home.getJTree().expandPath(home.getJTree().getPathForRow(j));
    }

    private void actualizarJTreeApendice (Apendice apendice) {
        MutableTreeNode node = new DefaultMutableTreeNode(apendice.getNombre() + " (" + apendice.getIdentificacion() + ")");
        DefaultTreeModel model = (DefaultTreeModel) home.getJTree().getModel();
        if (modificadoApendice == false)
            model.insertNodeInto(node, insertNode, insertIndex);

        // Expande el JTree
        for (int j = 0; j < home.getJTree().getSize().height; j++)
            home.getJTree().expandPath(home.getJTree().getPathForRow(j));
    }

    private void jRadioButton_seccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton_seccionActionPerformed
        if(jRadioButton_seccion.isSelected()){
            jLabel_identificador.setText("SEC-");
            //Calcular por que numero va.
            ident = this.home.documentoRequisitos.getNuevoIdentificadorSeccion();
            this.jTextField_identificacion.setText(ident);
        }
    }//GEN-LAST:event_jRadioButton_seccionActionPerformed

    private void jRadioButton_apendiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton_apendiceActionPerformed
       if(jRadioButton_apendice.isSelected()){
            jLabel_identificador.setText("APE-");
            //Calcular por que numero va.
            ident = this.home.documentoRequisitos.getNuevoIdentificadorApendice();
            this.jTextField_identificacion.setText(ident);
       }
    }//GEN-LAST:event_jRadioButton_apendiceActionPerformed



    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jfSeccion_Apendice().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup;
    private javax.swing.JButton jButton_aceptar;
    private javax.swing.JButton jButton_anadirAutor;
    private javax.swing.JButton jButton_anadirFuente;
    private javax.swing.JButton jButton_cancelar;
    private javax.swing.JButton jButton_eliminarAutor;
    private javax.swing.JButton jButton_eliminarFuente;
    private javax.swing.JCheckBox jCheckBox_ordenar;
    private com.toedter.calendar.JDateChooser jDateChooserFecha;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel_identificador;
    private javax.swing.JList jList_autores;
    private javax.swing.JList jList_fuentes;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel23;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JRadioButton jRadioButton_apendice;
    private javax.swing.JRadioButton jRadioButton_seccion;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextArea jTextArea_comentarios;
    private javax.swing.JTextField jTextField_identificacion;
    private javax.swing.JTextField jTextField_nombre;
    private javax.swing.JTextField jTextField_versionDer;
    private javax.swing.JTextField jTextField_versionIzq;
    // End of variables declaration//GEN-END:variables

    

    public void update(Observable o, Object arg) {
            home.actualizarTextPane();
    }

}
