/*
 *  SCORM_AdaptationEditorDialog.java
 *
 *  RELOAD Editor - An IMS Metadata, Content Packaging and Learning Design tool
 *  with ADAPTATION AT ACTIVITY LEVEL
 *
 *  Copyright (c) 2006 Miguel Fernández Lores
 *
 *  Technical Contact:
 *  Miguel Fernández Lores
 *  e-mail: tucias@hotmail.com
 *
 */

package uk.ac.reload.editor.scormadaptive.rules;
import uk.ac.reload.editor.EditorFrame;
import uk.ac.reload.editor.scormadaptive.rules.jdom.criterion.*;
import uk.ac.reload.editor.scormadaptive.rules.jdom.rule.*;
import uk.ac.reload.editor.scormadaptive.rules.user.userAction;
import uk.ac.reload.editor.scormadaptive.rules.syntax.*;
import uk.ac.reload.editor.scormadaptive.rules.tools.SpecialDialog;
import uk.ac.reload.editor.contentpackaging.xml.ContentPackage;
import java.awt.image.ColorModel;
import java.io.File;

import java.io.FileOutputStream;
import javax.swing.event.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.jdom.*;
import org.jdom.filter.ElementFilter;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/**
 * The SCORM Adaptation at Activity Level Assistant
 * Is the rule assistant. Helps the user to make the adaptation
 * at activity level rules
 *
 * @author  lagar
 * @version 0.2
 */
public class AdaptiveRules_EditorDialog extends JDialog {
    
    /**
     * Rule Manager
     */
    private RuleManager oRM;
    
    private ContentPackage cp;
    private Namespace namespace;
    
    /**
     * Criterion Manager
     */
    private CriterionManager oCM;
    
    /**
     * Criterion Object
     */
    private Criterion oCriterion;
    
    /**
     * Adaptation Criteria List
     */
    private ArrayList<adaptationCriterion> adaptationCriteria;
    
    /**
     * Constantes
     */
    final private static int NONE=0;
    final private static int EQUALS=1;
    final private static int ALL=2;
    
    final private static int ORGANIZATIONS=0;
    final private static int ORGANIZATION=1;
    final private static int ITEM=2;
    
    final public static String sTAB = "       ";
    
    /**
     * Type of operators active now
     */
    private int iOperatorsType=-1;
    
    /**
     * All the operators
     */
    final private static String[] oOperatorsAll={"==","<=",">=","<",">"}; //,"IN"};
    
    /**
     * Equals operator
     */
    final private static String[] oOperatorsEquals={"=="};
    
    /**
     * Frame Manager
     */
    public static JFrame oFManager;
    
    /**
     * Boolean variable. True if this Editor was launched by "Add Adaptation" action
     */
    protected boolean bEmpty;
    
    /**
     * Boolean variable. True if there are rule default.
     */
    protected boolean bDefault=false;
    
    /**
     * The JDOM Element edited
     */
    protected Element oFatherElement;
    protected Integer iFatherType;
    protected String sFatherTitle = "";
    
    boolean rightSetup = false;
    
    /**
     * List of Strings that represents the lines of the _ruleTextBox
     */
    protected String[] ruleText;
    
    /**
     * List Model of the list of activitys
     */
    protected DefaultListModel oModelAct;
    
    /**
     * Array of the Activity objects
     */
    protected ArrayList<Activity> oActivities;
    
    /**
     * Boolean variable. True if the user is working in the activities zone
     */
    protected boolean inAction = false;
    
    /**
     * The unique identifier assigned to this set of adaptation information
     */
    protected String sAdaptationID = null;
    
    /**
     * Reference to a unique identifier assigned to this set of adaptation information
     */
    protected String sAdaptationIDRef = null;
    
    /**
     * Constructor.
     * Creates new form SCORM_AdaptationEditorDialog
     */
    public AdaptiveRules_EditorDialog(JFrame frame, Element father, ContentPackage contentPackage) throws Exception {
    	
        super(frame, true);
        cp = contentPackage;
        namespace = cp.getTargetNamespace();
        
        Element oAdaptElement = father.getChild("adaptation", Namespace.getNamespace("http://idtv.det.uvigo.es"));  
        java.util.List previusElements = oAdaptElement.getChildren();
        if (previusElements == null || previusElements.size() <= 0) {
        	bEmpty = true;
        } else bEmpty = false;
        
        oFManager = frame;
        oFatherElement = father;
        //bEmpty = empty;
        oCM = new CriterionManager();
        oRM = new RuleManager(oFatherElement, namespace);
        java.util.List oListLE;        
        initComponents();
        oModelAct = new DefaultListModel();
        
        // Dialog Size
        setSize(EditorFrame.getInstance().getWidth() * 3/4, EditorFrame.getInstance().getHeight() * 3/4);
        setLocationRelativeTo(EditorFrame.getInstance());
        
        
/*        Document doc = new Document();
        doc.setRootElement((Element)father.clone());
        oFatherElement = doc.getRootElement(); */
        
        if (oFatherElement.getName().equals("organizations")) {
            iFatherType = ORGANIZATIONS;
            sFatherTitle = "Organizations";
            oListLE = oFatherElement.getChildren("organization", namespace);
        } else if (oFatherElement.getName().equals("organization")) {
            iFatherType = ORGANIZATION;
            sFatherTitle = "Organization: " + oFatherElement.getChild("title",namespace).getText();
            oListLE = oFatherElement.getChildren("item", namespace);
        } else if (oFatherElement.getName().equals("item")) {
            iFatherType = ITEM;
            sFatherTitle = "Activity: " + oFatherElement.getChild("title",namespace).getText();
            oListLE = oFatherElement.getChildren("item", namespace);
        } else {
        	System.out.println("Elemento padre no válido: " + oFatherElement.toString());
        	oListLE = null;
        }
               
        // Look for activities or organizations (if the father element is ORGANIZATIONS type)
        Iterator oIt = oListLE.iterator();
        int[] oIndices = new int[oListLE.size()];;
        int i=0;
        int iType;
        
        while (oIt.hasNext()){
            Element oEl = (Element)oIt.next();
            
            if(iFatherType == ORGANIZATIONS) iType = Activity.ORGANIZATION;
            else if (oEl.getChildren("item",namespace) != null) iType = Activity.ACTWITHCHILD;
            else iType = Activity.ACTCHILD;
            
            String sTitle = "";
            if (oEl.getChild("title",namespace) != null) sTitle = oEl.getChild("title",namespace).getText();
            
            if (oEl.getAttribute("identifier") == null) {
                throw new Exception("Item: Attribute identifier is mandatory");
            }
            
            String sIdentifier = oEl.getAttribute("identifier").getValue();            
            
            Activity oAct = new Activity(sTitle, sIdentifier, iType);
            if (oActivities == null) oActivities = new ArrayList<Activity>();
            oActivities.add(oAct);
            oModelAct.addElement(oAct.getToShow());
            
            oIndices[i]=i;
            i++;
        }
      
        //System.out.println("Número de actividades: " + oModelAct.size() );
        if (oModelAct == null || oModelAct.size()==0)  {
        	
        	JOptionPane.showMessageDialog(this, "There are not activities nor organizations in order to edit this element", "", JOptionPane.WARNING_MESSAGE);
        	//throw new Exception("Must have activitys or organizations to be shown");
        	return;
        }
        
        //System.out.println("*");
        // Actualizamos la lista de actividades u organizaciones
        _ruleActionList.setModel(oModelAct);
        _ruleActionList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        
        setResizable(false);
        setTitle("Editing Adaptation Rules => " + sFatherTitle);
        
        // _ruleListBox configuration
        _ruleListBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        _ruleListBox.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent oE) {
                ruleSelected(oE);
            }
        });
        _ruleListBox.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent oEvent) {
                if (oEvent.getClickCount() > 1) {
                    // If were more than 1 click => Change the name
                    mouse(oEvent);
                }
            }
        });
        

        DefaultListModel oModel = new DefaultListModel();
        //System.out.println("**");
      
        disableAllComponents();
        if (bEmpty) {
        	//System.out.println("----  MEEE");
            adaptationCriteria = null;
        } else {
            Element oElAdap = oFatherElement.getChild("adaptation", Namespace.getNamespace("http:\\idtv.det.uvigo.es"));
            if (oElAdap!=null) {
                if (oElAdap.getAttribute("ID")!=null)
                    sAdaptationID = oElAdap.getAttribute("ID").getValue();
                if (oElAdap.getAttribute("IDRef")!=null)
                    sAdaptationIDRef = oElAdap.getAttribute("IDRef").getValue();
                Element oElAC = oElAdap.getChild("adaptationParameters");
                if (oElAC==null) {
                    //0 or more times in the adaptation Element
                    adaptationCriteria = null;
                } else {
                    java.util.List oListAC = oElAC.getChildren("adaptationParameter");
                    oIt = oListAC.iterator();
                    if (oListAC == null) {
                        throw new Exception("adaptationParameters: Child Elements <adaptationParameter>" +
                                " are mandatory");
                    }
                    while (oIt.hasNext()) {
                        Element oElAux = (Element)oIt.next();
                        Element oElSource = oElAux.getChild("source");
                        Element oElValue = oElAux.getChild("value");
                        if ((oElSource == null)||(oElValue == null)) {
                            throw new Exception("adaptationParameter: Child Elements <source>" +
                                    " and <value> are mandatory");
                        }
                        adaptationCriterion oAC = new adaptationCriterion(oElValue.getText(), oElSource.getText());
                        if (adaptationCriteria == null) adaptationCriteria = new ArrayList<adaptationCriterion>();
                        adaptationCriteria.add(oAC);
                    }
                }
            }

            // Loof for rules
            bDefault = false;
            //System.out.println("Número de reglas preexistentes: "+ oRM.sizeRules());
            
            for (i=0; i<oRM.sizeRules(); i++) {
                oModel.addElement(oRM.getRule(i).getName());
                if (oRM.getRule(i).getName() == "Default") bDefault = true;
            }
            if (bDefault) jButtonDefault.setEnabled(false);
            
            _ruleListBox.setModel(oModel);
            //Seleccionamos la primera
            _ruleListBox.setSelectedIndex(0);
            actTextBox(oRM.getRule(0).getRuleText());
            jButtonDeleteRule.setEnabled(true);
        }
        jCBParameter.setModel(new DefaultComboBoxModel(oCM.getCriterionNames()));
        jCBParameter.setSelectedIndex(-1);
        rightSetup = true;
    }
    Rule r;
    
    public boolean getRightSetup() {
    	return rightSetup;
    }
    
    
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        _ruleListBox = new javax.swing.JList();
        jButtonNewRule = new javax.swing.JButton();
        jButtonDeleteRule = new javax.swing.JButton();
        jButtonValidateRule = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabelValue = new javax.swing.JLabel();
        jCBParameter = new javax.swing.JComboBox();
        jCBValue = new javax.swing.JComboBox();
        jLabelOperator = new javax.swing.JLabel();
        jCBOperator = new javax.swing.JComboBox();
        jButtonCreate = new javax.swing.JButton();
        jLabelPoint = new javax.swing.JLabel();
        jCBComplex = new javax.swing.JComboBox();
        jCBComplexValue = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jButtonAND = new javax.swing.JButton();
        jButtonOR = new javax.swing.JButton();
        jButtonNOT = new javax.swing.JButton();
        jButtonXOR = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTALogicalExpr = new javax.swing.JTextArea();
        jPanel4 = new javax.swing.JPanel();
        _actionRuleList = new javax.swing.JScrollPane();
        _ruleActionList = new javax.swing.JList();
        jButtonFinish = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jButtonBack = new javax.swing.JButton();
        jButtonSelect = new javax.swing.JButton();
        jSpinnerSelect = new javax.swing.JSpinner();
        jButtonDone = new javax.swing.JButton();
        jButtonDefault = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        _ruleListBox.setFont(new java.awt.Font("Tahoma", 1, 11));
        _ruleListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        _ruleListBox.setToolTipText("List of existing rules");
        _ruleListBox.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                _ruleListBoxValueChanged(evt);
            }
        });

        jScrollPane1.setViewportView(_ruleListBox);

        jButtonNewRule.setText("NewRule");
        jButtonNewRule.setToolTipText("Create a new adaptation rule.");
        jButtonNewRule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewRuleActionPerformed(evt);
            }
        });

        jButtonDeleteRule.setText("DeleteRule");
        jButtonDeleteRule.setToolTipText("Delete selected rule");
        jButtonDeleteRule.setEnabled(false);
        jButtonDeleteRule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteRuleActionPerformed(evt);
            }
        });

        jButtonValidateRule.setText("ValidateRule");
        jButtonValidateRule.setToolTipText("Validate the selected rule");
        jButtonValidateRule.setEnabled(false);
        jButtonValidateRule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonValidateRuleActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Expression", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
        jPanel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Criterion");

        jLabelValue.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabelValue.setText("Value");

        jCBParameter.setToolTipText("Select the adaptation criterion");
        jCBParameter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCBParameterActionPerformed(evt);
            }
        });

        jCBValue.setToolTipText("Selectd the adaptation criterion value");

        jLabelOperator.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabelOperator.setText("Operator");

        jCBOperator.setToolTipText("Select the operator to apply to selected adaptation criterion");
        jCBOperator.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCBOperatorActionPerformed(evt);
            }
        });

        jButtonCreate.setText("Create");
        jButtonCreate.setToolTipText("Adds the selected criterion to the rule conditions");
        jButtonCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCreateActionPerformed(evt);
            }
        });

        jLabelPoint.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabelPoint.setText(".");

        jCBComplex.setToolTipText("Select the adaptation criterion");
        jCBComplex.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCBComplexActionPerformed(evt);
            }
        });

        jCBComplexValue.setToolTipText("Select the complex adaptation criterion value");
        jCBComplexValue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCBComplexValueActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(jLabelValue))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jCBValue, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jCBParameter, 0, 154, Short.MAX_VALUE))
                .add(4, 4, 4)
                .add(jLabelPoint)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jCBComplex, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 52, Short.MAX_VALUE)
                        .add(jLabelOperator)
                        .add(15, 15, 15))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jCBComplexValue, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(jButtonCreate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jCBOperator, 0, 91, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel1)
                        .add(jCBParameter, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jLabelPoint)
                        .add(jCBComplex, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jCBOperator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jLabelOperator)))
                .add(14, 14, 14)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabelValue)
                    .add(jCBValue, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButtonCreate)
                    .add(jCBComplexValue, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(30, 30, 30))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Logical operators", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
        jButtonAND.setText("AND");
        jButtonAND.setEnabled(false);
        jButtonAND.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonANDActionPerformed(evt);
            }
        });

        jButtonOR.setText("OR");
        jButtonOR.setEnabled(false);
        jButtonOR.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonORActionPerformed(evt);
            }
        });

        jButtonNOT.setText("NOT");
        jButtonNOT.setEnabled(false);
        jButtonNOT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNOTActionPerformed(evt);
            }
        });

        jButtonXOR.setText("XOR");
        jButtonXOR.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonXORActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jButtonAND)
                .add(17, 17, 17)
                .add(jButtonOR)
                .add(15, 15, 15)
                .add(jButtonNOT)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 18, Short.MAX_VALUE)
                .add(jButtonXOR)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonXOR)
                    .add(jButtonNOT)
                    .add(jButtonOR)
                    .add(jButtonAND))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Logical expresion", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
        jTALogicalExpr.setColumns(20);
        jTALogicalExpr.setEditable(false);
        jTALogicalExpr.setFont(new java.awt.Font("Tahoma", 1, 11));
        jTALogicalExpr.setRows(5);
        jScrollPane2.setViewportView(jTALogicalExpr);

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 595, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Action", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
        _actionRuleList.setViewportView(_ruleActionList);

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .add(_actionRuleList, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 595, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .add(_actionRuleList, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButtonFinish.setText("Finish");
        jButtonFinish.setToolTipText("Save changes and return");
        jButtonFinish.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFinishActionPerformed(evt);
            }
        });

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Others", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
        jButtonBack.setText("BACK");
        jButtonBack.setEnabled(false);
        jButtonBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBackActionPerformed(evt);
            }
        });

        jButtonSelect.setText("SELECT");
        jButtonSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSelectActionPerformed(evt);
            }
        });

        jButtonDone.setText("DONE");
        jButtonDone.setToolTipText("End the ruleConditions and form the ruleActions");
        jButtonDone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDoneActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .add(jButtonDone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 69, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(17, 17, 17)
                .add(jButtonSelect)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSpinnerSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 33, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 18, Short.MAX_VALUE)
                .add(jButtonBack, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 74, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonDone)
                    .add(jButtonSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jSpinnerSelect, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                    .add(jButtonBack))
                .addContainerGap())
        );

        jButtonDefault.setText("DefaultRule");
        jButtonDefault.setToolTipText("Create the default adaptation rule");
        jButtonDefault.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDefaultActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jButtonValidateRule, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jButtonDeleteRule, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                    .add(jButtonNewRule, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                    .add(jButtonDefault, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                    .add(jButtonFinish, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE))
                .add(16, 16, 16)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 17, Short.MAX_VALUE)
                        .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 275, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(19, 19, 19)
                        .add(jButtonDefault)
                        .add(15, 15, 15)
                        .add(jButtonNewRule)
                        .add(15, 15, 15)
                        .add(jButtonDeleteRule)
                        .add(16, 16, 16)
                        .add(jButtonValidateRule))
                    .add(layout.createSequentialGroup()
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 113, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(6, 6, 6)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButtonFinish)
                    .add(layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCBComplexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCBComplexActionPerformed
        try {
            // Vemos cual es el parámetro seleccionado
            // Seleccionamos el combo con los operadores seleccionables
            // en función del tipo de parámetro
            
            //Si es -1 no hay ninguno seleccionado => salimos
            int iIndex = jCBComplex.getSelectedIndex();
            if (iIndex == -1) return;
            ComplexCriterion oComplex = oCM.getComplex(oCM.getCriterion(jCBParameter.getSelectedIndex()).getName());
            Criterion oCriterion = oComplex.getCriterion(iIndex);
            if (oComplex == null) return;
            switch (oCriterion.getType()) {
                
                case Criterion.STATE:
                case Criterion.LANGCODE:
                    jCBOperator.setModel(new DefaultComboBoxModel(oOperatorsEquals));
                    jCBOperator.setVisible(true);
                    jLabelOperator.setVisible(true);
                    
                    jCBComplexValue.setModel(new DefaultComboBoxModel(oCriterion.getValues()));
                    jCBComplexValue.setVisible(true);
                    
                    //falta seleccionar una por defecto
                    jButtonCreate.setEnabled(true);
                    break;
                case Criterion.INTEGER:
                    jCBOperator.setModel(new DefaultComboBoxModel(oOperatorsAll));
                    jCBOperator.setVisible(true);
                    jLabelOperator.setVisible(true);
                    
                    jCBComplexValue.setModel(new DefaultComboBoxModel(oCriterion.getValues()));
                    jCBComplexValue.setVisible(true);
                    
                    //falta seleccionar una por defecto
                    jButtonCreate.setEnabled(true);
                    break;
                case Criterion.COMPLEX:
                    //No debería entrar aquí
                    //No debería haber tipos complex dentro de otros complex...?
                    break;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            java.awt.Toolkit.getDefaultToolkit().beep();
            System.exit(-1);
        }
    }//GEN-LAST:event_jCBComplexActionPerformed

    private void jButtonCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCreateActionPerformed
        try {
            String sOperator = oOperatorsAll[jCBOperator.getSelectedIndex()];
            String sSource = oCM.getVocabularyName();
            
            Rule oRuleSelected = oRM.getRule(oRM.iRuleSelected);
            oRuleSelected.iCriteriaUsed++;
            
            if (jCBComplex.isVisible()) {
                //Es un Criterion de tipo complejo
                String sValue = oCM.getComplex(oCM.getCriterion(jCBParameter.getSelectedIndex()).getName()).getValues()[jCBValue.getSelectedIndex()];
                
                //Creamos la nueva userAction
                userAction ouA = new userAction(oRuleSelected, jTALogicalExpr.getText(), userAction.CREATECOMPLEX);
                //Guarda los indices que estaban seleccionados
                ouA.actualizeIndices(jCBParameter.getSelectedIndex(),
                        jCBOperator.getSelectedIndex(),
                        jCBValue.getSelectedIndex(),
                        jCBComplex.getSelectedIndex(),
                        jCBComplexValue.getSelectedIndex());
                //Añadimos la accion de usuario a la pila
                oRuleSelected.pushUserAction(ouA);
                
                // Example:
                // if (spanish.reading_level >= 5) ...
                //
                // <ruleCondition>
                //      <adaptationCriterion>
                //              <source> ... </source> <value> languages.k.language </value>
                //      </adaptationCriterion>
                //      <comparative operator = "equals"> es </comparative>
                // </ruleCondition>
                // <ruleCondition>
                //      <adaptationCriterion>
                //              <source> ... </source> <value> languages.k.reading_level </value>
                //      </adaptationCriterion>
                //      <comparative operator = "moreEqualThan"> 5 </comparative>
                // </ruleCondition>
                //
                
                String sCriterion = oCM.getCriterion(jCBParameter.getSelectedIndex()).getName();
                // (Example) sCriterion = "languages"
                ComplexCriterion oComplex = oCM.getComplex(sCriterion);
                String sComplex = oComplex.getCriterion(jCBComplex.getSelectedIndex()).getName();
                // (Example)  sComplex = "reading_level"
                sCriterion = oComplex.getName();
                // (Example) sCriterion = "language"
                adaptationCriterion oaC = new adaptationCriterion(oComplex.getPrefixComplex() + "." + sCriterion, sSource);
                // (Example) oComplex.getPrefixComplex() = "languages.k"
                oRuleSelected.addAdaptationCriterion(oaC);
                RuleCondition orC = new RuleCondition(oaC,"==",sValue,"noOp");
                // (Example) sValue = "es"
                oRuleSelected.addRuleCondition(orC);
                
                Criterion oCriterion = oComplex.getCriterion(jCBComplex.getSelectedIndex());
                String sComplexValue = oCriterion.getValues()[jCBComplexValue.getSelectedIndex()];
                oaC = new adaptationCriterion(oComplex.getPrefixComplex() + "."  + sComplex, sSource);
                oRuleSelected.addAdaptationCriterion(oaC);
                orC = new RuleCondition(oaC,sOperator,sComplexValue,"noOp");
                // (Example) sOperator = ">="
                // (Example) sComplexValue = "5"
                oRuleSelected.addRuleCondition(orC);
                
                //Almacenamos el numero de criterion usados
                //para saber en que linea tenemos que añadir!
                int iIndex = oRuleSelected.iCriteriaUsed - 1;
                String[] ruleText = oRuleSelected.getRuleText();
                
                //Actualizamos el cuadro de texto
                ruleText[iIndex] += sValue + "." + sComplex + " " + sOperator + " " + sComplexValue + ")";
                actTextBox(ruleText);
                oRuleSelected.changeRuleText(ruleText);
                
                //Habilitamos e inhabilitamos lo que corresponda
                actComponents(ouA.getType());
            } else {
                String sCriterion = oCM.getCriterion(jCBParameter.getSelectedIndex()).getName();
                String sValue = oCM.getCriterion(jCBParameter.getSelectedIndex()).getValues()[jCBValue.getSelectedIndex()];
                
                //Creamos la nueva userAction
                userAction ouA = new userAction(oRuleSelected, jTALogicalExpr.getText(), userAction.CREATE);
                //Guarda los indices que estaban seleccionados
                ouA.actualizeIndices(jCBParameter.getSelectedIndex(),
                        jCBOperator.getSelectedIndex(),
                        jCBValue.getSelectedIndex());
                //Añadimos la accion de usuario a la pila
                oRuleSelected.pushUserAction(ouA);
                
                adaptationCriterion oaC = new adaptationCriterion(sCriterion, sSource);
                oRuleSelected.addAdaptationCriterion(oaC);
                RuleCondition orC = new RuleCondition(oaC,sOperator,sValue,"noOp");
                oRuleSelected.addRuleCondition(orC);
                
                //Almacenamos el numero de criterion usados
                //para saber en que linea tenemos que añadir!
                int iIndex = oRuleSelected.iCriteriaUsed - 1;
                String[] ruleText = oRuleSelected.getRuleText();
                
                //Actualizamos el cuadro de texto
                ruleText[iIndex] += sCriterion + " " + sOperator + " " + sValue + ")";
                actTextBox(ruleText);
                oRuleSelected.changeRuleText(ruleText);
                
                //Habilitamos e inhabilitamos lo que corresponda
                actComponents(ouA.getType());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            java.awt.Toolkit.getDefaultToolkit().beep();
            System.exit(-1);
        }
    }//GEN-LAST:event_jButtonCreateActionPerformed
    
    private void jCBComplexValueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCBComplexValueActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_jCBComplexValueActionPerformed
        
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        close();
    }//GEN-LAST:event_formWindowClosing
    
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        //TODO add your handling code here:
    }//GEN-LAST:event_formWindowClosed
    
    private void jCBOperatorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCBOperatorActionPerformed
        //Vemos cual es el parámetro seleccionado
        //Seleccionamos el combo con los operadores seleccionables en función del tipo de parámetro
        String sOp = oOperatorsAll[jCBOperator.getSelectedIndex()];
    }//GEN-LAST:event_jCBOperatorActionPerformed
    
    private void jCBParameterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCBParameterActionPerformed
        // Vemos cual es el parámetro seleccionado
        // Seleccionamos el combo con los operadores seleccionables
        // en función del tipo de parámetro
        
        //Si es -1 no hay ninguno seleccionado => salimos
        if (jCBParameter.getSelectedIndex() == -1) return;
        oCriterion = oCM.getCriterion(jCBParameter.getSelectedIndex());
        switch (oCriterion.getType()) {
            
            case Criterion.STATE:
            case Criterion.LANGCODE:
                jCBOperator.setModel(new DefaultComboBoxModel(oOperatorsEquals));
                jCBOperator.setVisible(true);
                jLabelOperator.setVisible(true);
                
                jCBValue.setModel(new DefaultComboBoxModel(oCriterion.getValues()));
                jCBValue.setVisible(true);
                jLabelValue.setVisible(true);
                
                //falta seleccionar una por defecto
                jButtonCreate.setEnabled(true);
                
                jLabelPoint.setVisible(false);
                jCBComplex.setVisible(false);
                jCBComplexValue.setVisible(false);
                break;
            case Criterion.INTEGER:
                jCBOperator.setModel(new DefaultComboBoxModel(oOperatorsAll));
                jCBOperator.setVisible(true);
                jLabelOperator.setVisible(true);
                
                jCBValue.setModel(new DefaultComboBoxModel(oCriterion.getValues()));
                jCBValue.setVisible(true);
                jLabelValue.setVisible(true);
                
                //falta seleccionar una por defecto
                jButtonCreate.setEnabled(true);
                
                jLabelPoint.setVisible(false);
                jCBComplex.setVisible(false);
                break;
            case Criterion.COMPLEX:
                ComplexCriterion oCC = oCM.getComplex(oCriterion.getName());
                jCBComplex.setModel(new DefaultComboBoxModel(oCC.getModelComplex()));
                jCBComplex.setVisible(true);
                jCBComplex.setSelectedIndex(-1);
                jLabelPoint.setVisible(true);
                
                jCBValue.setModel(new DefaultComboBoxModel(oCC.getValues()));
                jCBValue.setVisible(true);
                jLabelValue.setVisible(true);
                
                jCBOperator.setVisible(false);
                jLabelOperator.setVisible(false);
                jCBComplexValue.setVisible(false);
                jButtonCreate.setEnabled(false);
                break;
        }
    }//GEN-LAST:event_jCBParameterActionPerformed
    
    private void jButtonFinishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFinishActionPerformed
        close();
    }//GEN-LAST:event_jButtonFinishActionPerformed
    
    private void jButtonBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBackActionPerformed
        Rule oRuleSelected = oRM.getRule(oRM.iRuleSelected);
        userAction oLastUserAction = oRuleSelected.popUserAction();
        
        //Volvemos al texto anterior
        if (oLastUserAction.getText() != null) {
            oRuleSelected.changeRuleText(oLastUserAction.getText());
            jTALogicalExpr.setText(oLastUserAction.getText());
        }
        
        //Habilitamos y desabilitamos según corresponda
        switch (oLastUserAction.getType()){
            case userAction.ANDACT:
            case userAction.ORACT:
            case userAction.XORACT:
                jButtonAND.setEnabled(true);
                //if (oRuleSelected.getUserActionsSize()==0) jButtonBack.setEnabled(false);
                //else jButtonBack.setEnabled(true);
                jButtonBack.setEnabled(false);
                jButtonNOT.setEnabled(false);
                jButtonOR.setEnabled(true);
                jButtonSelect.setText("SELECT");
                jButtonSelect.setEnabled(true);
                jButtonXOR.setEnabled(true);
                jSpinnerSelect.setEnabled(true);
                oModelAct.removeElementAt(oModelAct.size()-1);
                break;
            case userAction.NOTACT:
                jButtonAND.setEnabled(false);
                //if (oRuleSelected.getUserActionsSize()==0) jButtonBack.setEnabled(false);
                //else jButtonBack.setEnabled(true);
                jButtonBack.setEnabled(false);
                jButtonNOT.setEnabled(true);
                jButtonOR.setEnabled(false);
                jButtonSelect.setText(" SHOW ");
                jButtonSelect.setEnabled(true);
                jButtonXOR.setEnabled(false);
                jSpinnerSelect.setEnabled(false);
                oModelAct.removeElementAt(oModelAct.size()-1);
                break;
            case userAction.CREATE:
                //Actualizamos los combobox
                int[] oIndices = oLastUserAction.getIndices();
                jCBParameter.setSelectedIndex(oIndices[0]);
                jCBOperator.setSelectedIndex(oIndices[1]);
                jCBValue.setSelectedIndex(oIndices[2]);
                jCBParameter.setEnabled(true);
                jCBOperator.setVisible(true);
                jCBValue.setVisible(true);
                jLabelOperator.setVisible(true);
                jLabelValue.setVisible(true);
                jButtonCreate.setEnabled(true);
                jButtonNOT.setEnabled(false);
                if (oRuleSelected.getUserActionsSize()==0) jButtonBack.setEnabled(false);
                else jButtonBack.setEnabled(true);
                jButtonDone.setEnabled(false);
                jButtonAND.setEnabled(false);
                jButtonOR.setEnabled(false);
                oRuleSelected.removeLastRuleCondition();
                oRuleSelected.removeLastCriterionUsed();
                oRuleSelected.iCriteriaUsed--;
                break;
            case userAction.CREATECOMPLEX:
                //Actualizamos los combobox
                oIndices = oLastUserAction.getIndices();
                jCBParameter.setSelectedIndex(oIndices[0]);
                jCBOperator.setSelectedIndex(oIndices[1]);
                jCBValue.setSelectedIndex(oIndices[2]);
                jCBComplex.setSelectedIndex(oIndices[3]);
                jCBComplexValue.setSelectedIndex(oIndices[4]);
                jCBParameter.setEnabled(true);
                jCBOperator.setVisible(true);
                jCBValue.setVisible(true);
                jCBComplex.setVisible(true);
                jCBComplexValue.setVisible(true);
                jLabelOperator.setVisible(true);
                jLabelValue.setVisible(true);
                jLabelPoint.setVisible(true);
                jButtonCreate.setEnabled(true);
                jButtonNOT.setEnabled(false);
                if (oRuleSelected.getUserActionsSize()==0) jButtonBack.setEnabled(false);
                else jButtonBack.setEnabled(true);
                jButtonDone.setEnabled(false);
                jButtonAND.setEnabled(false);
                jButtonOR.setEnabled(false);
                oRuleSelected.removeLastRuleCondition();
                oRuleSelected.removeLastRuleCondition();
                oRuleSelected.removeLastCriterionUsed();
                oRuleSelected.removeLastCriterionUsed();
                oRuleSelected.iCriteriaUsed--;
                break;
            case userAction.DONE:
                inAction = false;
                jButtonSelect.setEnabled(false);
                jSpinnerSelect.setEnabled(false);
                if (oRuleSelected.getRuleConditions().getOperatorLast().equals("not")) jButtonNOT.setEnabled(false);
                else jButtonNOT.setEnabled(true);
                jButtonDone.setEnabled(true);
                
                if (oRuleSelected.getCombination().equals("and")) {
                    jButtonAND.setEnabled(true);
                    jButtonOR.setEnabled(false);
                } else if (oRuleSelected.getCombination().equals("or")) {
                    jButtonOR.setEnabled(true);
                    jButtonAND.setEnabled(false);
                } else {
                    jButtonAND.setEnabled(true);
                    jButtonOR.setEnabled(true);
                }
                
                _ruleActionList.setEnabled(false);
                jButtonXOR.setEnabled(false);
                break;
            case userAction.ORCRI:
            case userAction.ANDCRI:
                jCBParameter.setEnabled(false);
                jCBOperator.setVisible(false);
                jCBValue.setVisible(false);
                jCBComplex.setVisible(false);
                jCBComplexValue.setVisible(false);
                jLabelOperator.setVisible(false);
                jLabelValue.setVisible(false);
                jLabelPoint.setVisible(false);
                jButtonCreate.setEnabled(false);
                jButtonNOT.setEnabled(true);
                jButtonBack.setEnabled(true);
                jButtonDone.setEnabled(true);
                
                if (oRuleSelected.getCriteriaUsed().size() == 1) {
                    oRuleSelected.setCombination("");
                    //By default
                    oRuleSelected.setCombination("all");
                }
                if (oRuleSelected.getCombination().equals("and")) {
                    jButtonAND.setEnabled(true);
                    jButtonOR.setEnabled(false);
                } else if (oRuleSelected.getCombination().equals("or")) {
                    jButtonOR.setEnabled(true);
                    jButtonAND.setEnabled(false);
                } else {
                    jButtonAND.setEnabled(true);
                    jButtonOR.setEnabled(true);
                }
                break;
            case userAction.SHOW:
                jButtonAND.setEnabled(false);
                if (oRuleSelected.getUserActionsSize()==0) jButtonBack.setEnabled(false);
                else jButtonBack.setEnabled(true);
                jButtonNOT.setEnabled(true); //esto cambia
                jButtonOR.setEnabled(false);
                jButtonSelect.setText(" SHOW ");
                jButtonSelect.setEnabled(true); //esto cambia
                jButtonXOR.setEnabled(false);
                jSpinnerSelect.setEnabled(false);
                jButtonValidateRule.setEnabled(false);
                _ruleActionList.setEnabled(true);
                break;
            case userAction.SELECT:
                jButtonAND.setEnabled(true);
                //if (oRuleSelected.getUserActionsSize()==0) jButtonBack.setEnabled(false);
                //else jButtonBack.setEnabled(true);
                jButtonBack.setEnabled(false);
                jButtonNOT.setEnabled(false);
                jButtonOR.setEnabled(false);
                jButtonSelect.setText("SELECT");
                jButtonSelect.setEnabled(true);
                jButtonXOR.setEnabled(true);
                jSpinnerSelect.setEnabled(true);
                oModelAct.removeElementAt(oModelAct.size()-1);
                break;
            case userAction.NOTCRI:
                jButtonNOT.setEnabled(true);
                break;
        }
    }//GEN-LAST:event_jButtonBackActionPerformed
    
    private void jButtonSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelectActionPerformed
        Rule oRuleSelected = oRM.getRule(oRM.iRuleSelected);
        
        if (jButtonSelect.getText() == "SELECT") {
            //The user clicks over SELECT
            int[] oIndices;
            ArrayList<Activity> oActSelected = null;
            
            oIndices=_ruleActionList.getSelectedIndices();
            if (oActSelected == null) oActSelected = new ArrayList<Activity>();
            for (int i=0; i<oIndices.length; i++){
                Activity oAct = oActivities.get(oIndices[i]);
                oActSelected.add(oAct);
            }
            LogicalExpression oLE = new LogicalExpression("select",
                    (Integer)jSpinnerSelect.getValue(),
                    oIndices.length, "noOp", oActSelected);
            Activity oActNew = new Activity(oLE.getNameToShow());
            oActNew.addLE(oLE);
            
            //La añadimos a la lista
            oModelAct.addElement(oActNew.getToShow());
            oRuleSelected.addActivity(oActNew);
            if (oActivities==null) oActivities = new ArrayList<Activity>();
            oActivities.add(oActNew);
            
            _ruleActionList.setModel(oModelAct);
            //Seleccionamos la última que es la nueva
            _ruleActionList.setSelectedIndex(oModelAct.size()-1);
            
            //Habilitamos e inhabilitamos lo que corresponda
            actComponents(userAction.SELECT);
        } else {
            //The user clicks over SHOW
            int iIndex=_ruleActionList.getSelectedIndex(); // En teoría solo puede ser 1 el seleccionado
            oRuleSelected.setSelectedAct(iIndex);
            
            //Creamos la nueva userAction
            userAction ouA = new userAction(oRuleSelected, jTALogicalExpr.getText(), userAction.SHOW);
            //Guarda los indices que estaban seleccionados
            ouA.actualizeIndices(iIndex);
            //Añadimos la accion de usuario a la pila
            oRuleSelected.pushUserAction(ouA);
            
            //Actualizamos el campo de texto
            Activity oActAux = oActivities.get(iIndex);
            int iLines = 0;
            
            if (oActAux.getType() == Activity.LOGICALEXP)
                iLines = oActivities.get(iIndex).getActImplicadas();
            else iLines = 1;
            ruleText = new String[oRuleSelected.getRuleText().length + iLines];
            for (int a = 0;a<oRuleSelected.getRuleText().length; a++)
                ruleText[a] = oRuleSelected.getRuleTextLine(a);
            iLines = oRuleSelected.getRuleText().length;
            ruleText[iLines] = sTAB + "show";
            
            //Guardamos el texto a mostrar dentro de Show()
            char[] cList = ("(" + oActAux.getToShow() + ");").toCharArray();
            int iAnt = 0;
            int iSum = 0;
            
            //Recorremos la cadena buscando donde terminan actividades
            //para introducir saltos de línea
            for (int i=0; i<cList.length-1; i++){
                //Cuando encontramos ") " acaba una actividad
                if ((cList[i]==')')&&(cList[i+1]==' ')) {
                    if (ruleText[iLines+iSum]==null) ruleText[iLines+iSum] = sTAB + sTAB;
                    for (int ii=iAnt; ii<=i+1; ii++) ruleText[iLines+iSum] += cList[ii];
                    iAnt = i+2;
                    iSum++;
                }
                //Comprobamos si es el ultimo
                else if ((cList[i+1]==';')&&(i+1==cList.length-1)) {
                    if (ruleText[iLines+iSum] == null) ruleText[iLines+iSum] = sTAB + sTAB;
                    for (int ii=iAnt; ii<=i+1; ii++) ruleText[iLines+iSum] += cList[ii];
                }
            }
            oRuleSelected.changeRuleText(ruleText);
            actTextBox(ruleText);
            //Habilitamos e inhabilitamos lo que corresponda
            actComponents(ouA.getType());
        }
    }//GEN-LAST:event_jButtonSelectActionPerformed
    
    private void jButtonDoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDoneActionPerformed
        //Pasamos a trabajar con Action
        inAction = true;
        Rule oRuleSelected = oRM.getRule(oRM.iRuleSelected);
        
        //Creamos la nueva userAction
        userAction ouA = new userAction(oRuleSelected, jTALogicalExpr.getText(), userAction.DONE);
        //Añadimos la accion de usuario a la pila
        oRuleSelected.pushUserAction(ouA);
        
        String[] ruleText = new String[oRuleSelected.getRuleText().length + 1];
        for (int i=0; i<oRuleSelected.getRuleText().length; i++){
            ruleText[i] = oRuleSelected.getRuleTextLine(i);
        }
        
        //Indice de la ultima fila del ruleText
        int iIndex = oRuleSelected.getRuleText().length - 1;
        
        //Actualizamos el panel de texto
        if (iIndex > 0) ruleText[iIndex] += ")";
        ruleText[iIndex+1] = new String("then");
        oRuleSelected.changeRuleText(ruleText);
        actTextBox(ruleText);
        
        //Seleccionamos todo en el _ruleActionList
        int[] oIndices = new int[oModelAct.size()];
        for (int i=0; i<oModelAct.size(); i++) oIndices[i] = i;
        
        _ruleActionList.setEnabled(true);
        _ruleActionList.setSelectedIndices(oIndices);
        //_ruleActionList.setCellRenderer(new RuleActionRenderer());
        _ruleActionList.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent oE) {
                actionSelected(oE);
            }
        });
        
        //-1 porque no tiene sentido Select x/x
        try {
        	jSpinnerSelect.setModel(new SpinnerNumberModel(1,1,oIndices.length-1,1));
        } catch (Exception e) {}
        //Habilitamos e inhabilitamos lo que corresponda
        actComponents(ouA.getType());
    }//GEN-LAST:event_jButtonDoneActionPerformed
    
    private void jButtonXORActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonXORActionPerformed
        //We are working with activities
        int[] oIndices;
        ArrayList<Activity> oActSelected = null;
        Rule oRuleSelected = oRM.getRule(oRM.iRuleSelected);
        
        oIndices =_ruleActionList.getSelectedIndices();
        //Creamos la nueva userAction
        userAction ouA = new userAction(oRuleSelected, jTALogicalExpr.getText(), userAction.XORACT);
        //Guarda los indices que estaban seleccionados
        //ouA.actualizeIndices(oIndices);
        //Añadimos la accion de usuario a la pila
        //oRuleSelected.pushUserAction(ouA);
        
        if (oActSelected == null) oActSelected = new ArrayList<Activity>();
        for (int i=0; i<oIndices.length; i++){
            Activity oAct = oActivities.get(oIndices[i]);
            oActSelected.add(oAct);
        }
        LogicalExpression oLE = new LogicalExpression("xor",-1,oIndices.length,"noOp",oActSelected);
        Activity oActNew = new Activity(oLE.getNameToShow());
        oActNew.addLE(oLE);
        
        //La añadimos a la lista
        oModelAct.addElement(oActNew.getToShow());
        oRuleSelected.addActivity(oActNew);
        oActivities.add(oActNew);
        
        _ruleActionList.setModel(oModelAct);
        //Seleccionamos la última que es la nueva
        _ruleActionList.setSelectedIndex(oModelAct.size()-1);
        
        //Habilitamos e inhabilitamos lo que corresponda
        actComponents(ouA.getType());
    }//GEN-LAST:event_jButtonXORActionPerformed
    
    private void jButtonNOTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNOTActionPerformed
        Rule oRuleSelected = oRM.getRule(oRM.iRuleSelected);
        
        if (inAction) {
            //We are working with activities
            int iIndex=_ruleActionList.getSelectedIndex(); // En teoría solo puede ser 1 el seleccionado
            
            //Creamos la nueva userAction
            userAction ouA = new userAction(oRuleSelected, userAction.NOTACT);
            //Guarda los indices que estaban seleccionados
            //ouA.actualizeIndices(iIndex);
            //Añadimos la accion de usuario a la pila
            //oRuleSelected.pushUserAction(ouA);
            
            Activity oActSelected = oActivities.get(iIndex);
            
            LogicalExpression oLE = new LogicalExpression(null, -1, 1, "not", oActSelected);
            Activity oActNew = new Activity(oLE.getNameToShow());
            oActNew.addLE(oLE);
            
            //La añadimos a la lista
            oModelAct.addElement(oActNew.getToShow());
            oRuleSelected.addActivity(oActNew);
            oActivities.add(oActNew);
            
            _ruleActionList.setModel(oModelAct);
            //Seleccionamos la última que es la nueva
            _ruleActionList.setSelectedIndex(oModelAct.size()-1);
            
            //Habilitamos e inhabilitamos lo que corresponda
            actComponents(ouA.getType());
        } else {
            //We are working with criterion
            
            //Creamos la nueva userAction
            userAction ouA = new userAction(oRuleSelected, jTALogicalExpr.getText(), userAction.NOTCRI);
            //Añadimos la accion de usuario a la pila
            oRuleSelected.pushUserAction(ouA);
            
            //We set the ruleCondition's operator attribute to "not"
            oRuleSelected.getRuleConditions().setOperatorLast("not");
            String[] ruleText = oRuleSelected.getRuleText();
            //Almacenamos el indice del ultimo
            //criterio introducido que es el que se está negando
            int iIndex = oRuleSelected.iCriteriaUsed-1;
            
            if (iIndex == 0) {
                //Almacenamos provisionalemente lo que viene tras 'if '
                //if (criterion1) ----> if (not(criterion1))
                String sAux = ruleText[iIndex].substring(4);
                ruleText[iIndex] = "if (not(" + sAux + ")";
            } else {
                if (oRuleSelected.getCombination() == "and") {
                    //Almacenamos provisionalemente lo que viene tras 'and '
                    //if ((criterion1)           if ((criterion1)
                    //    and (criterion2) ---->     and (not(criterion2))
                    String sAux = ruleText[iIndex].substring(10);
                    ruleText[iIndex] = sTAB + "and (not" + sAux + ")";
                } else {
                    //Almacenamos provisionalemente lo que viene tras 'or '
                    //if ((criterion1)           if ((criterion1)
                    //    or (criterion2) ---->     or (not(criterion2))
                    String sAux = ruleText[iIndex].substring(9);
                    ruleText[iIndex] = sTAB + "or (not" + sAux + ")";
                }
            }
            actTextBox(ruleText);
            oRuleSelected.changeRuleText(ruleText);
            actComponents(ouA.getType());
        }
    }//GEN-LAST:event_jButtonNOTActionPerformed
    
    private void jButtonORActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonORActionPerformed
        Rule oRuleSelected = oRM.getRule(oRM.iRuleSelected);
        
        if (inAction) {
            //We are working with activities
            int[] oIndices;
            ArrayList<Activity> oActSelected = null;
            
            oIndices=_ruleActionList.getSelectedIndices();
            //Creamos la nueva userAction
            userAction ouA = new userAction(oRuleSelected, userAction.ORACT);
            //Guarda los indices que estaban seleccionados
            //ouA.actualizeIndices(oIndices);
            //Añadimos la accion de usuario a la pila
            //oRuleSelected.pushUserAction(ouA);
            
            if (oActSelected == null) oActSelected = new ArrayList<Activity>();
            for (int i=0; i<oIndices.length; i++){
                Activity oAct = oActivities.get(oIndices[i]);
                oActSelected.add(oAct);
            }
            LogicalExpression oLE = new LogicalExpression("or",-1,oIndices.length,"noOp",oActSelected);
            Activity oActNew = new Activity(oLE.getNameToShow());
            oActNew.addLE(oLE);
            
            //La añadimos a la lista
            oModelAct.addElement(oActNew.getToShow());
            oRuleSelected.addActivity(oActNew);
            oActivities.add(oActNew);
            
            _ruleActionList.setModel(oModelAct);
            //Seleccionamos la última que es la nueva
            _ruleActionList.setSelectedIndex(oModelAct.size()-1);
            
            //Habilitamos e inhabilitamos lo que corresponda
            actComponents(ouA.getType());
        } else {
            //We are working with criteria
            //Creamos la nueva userAction
            userAction ouA = new userAction(oRuleSelected, jTALogicalExpr.getText(), userAction.ORCRI);
            //Añadimos la accion de usuario a la pila
            oRuleSelected.pushUserAction(ouA);
            //Almacenamos el numero de criterion usados
            //para saber en que linea tenemos que añadir!
            int iIndex = oRuleSelected.iCriteriaUsed;
            String[] ruleText = new String[oRuleSelected.getRuleText().length+1];
            for(int i=0; i<ruleText.length-1; i++){
                ruleText[i] = oRuleSelected.getRuleTextLine(i);
            }
            
            if (iIndex == 1) {
                //Almacenamos provisionalemente lo que viene tras 'if '
                //if (criterion1) ----> if ((criterion1)
                //                          or (
                String sAux = ruleText[0].substring(3);
                ruleText[0] = "if (" + sAux;
                
                oRuleSelected.setCombination("or");
                oRuleSelected.getRuleConditions().setConditionCombination("any");
            }
            ruleText[iIndex] = new String(sTAB + "or (");
            
            actTextBox(ruleText);
            oRuleSelected.changeRuleText(ruleText);
            //Habilitamos e inhabilitamos lo que corresponda
            actComponents(ouA.getType());
        }
    }//GEN-LAST:event_jButtonORActionPerformed
    
    private void jButtonANDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonANDActionPerformed
        Rule oRuleSelected = oRM.getRule(oRM.iRuleSelected);
        
        if (inAction) {
            //We are working with activities
            int[] oIndices;
            ArrayList<Activity> oActSelected = null;
            
            oIndices = _ruleActionList.getSelectedIndices();
            
            //Creamos la nueva userAction
            userAction ouA = new userAction(oRuleSelected, userAction.ANDACT);
            //Guarda los indices que estaban seleccionados
            //ouA.actualizeIndices(oIndices);
            //Añadimos la accion de usuario a la pila
            //oRuleSelected.pushUserAction(ouA);
            
            if (oActSelected == null) oActSelected = new ArrayList<Activity>();
            for (int i=0; i<oIndices.length; i++){
                Activity oAct = oActivities.get(oIndices[i]);
                oActSelected.add(oAct);
            }
            LogicalExpression oLE = new LogicalExpression("and",-1,oIndices.length,"noOp",oActSelected);
            Activity oActNew = new Activity(oLE.getNameToShow());
            oActNew.addLE(oLE);
            
            //La añadimos a la lista
            oModelAct.addElement(oActNew.getToShow());
            oRuleSelected.addActivity(oActNew);
            oActivities.add(oActNew);
            
            _ruleActionList.setModel(oModelAct);
            //Seleccionamos la última que es la nueva
            _ruleActionList.setSelectedIndex(oModelAct.size()-1);
            
            //Habilitamos e inhabilitamos lo que corresponda
            actComponents(ouA.getType());
        } else {
            //We are working with criteria
            //Almacenamos el numero de criterion usados
            //para saber en que linea tenemos que añadir!
            
            //Creamos la nueva userAction
            userAction ouA = new userAction(oRuleSelected, jTALogicalExpr.getText(), userAction.ANDCRI);
            //Añadimos la accion de usuario a la pila
            oRuleSelected.pushUserAction(ouA);
            //Habilitamos e inhabilitamos lo que corresponda
            
            int iIndex = oRuleSelected.iCriteriaUsed;
            String[] ruleText = new String[oRuleSelected.getRuleText().length+1];
            for(int i=0; i<ruleText.length-1; i++){
                ruleText[i] = oRuleSelected.getRuleTextLine(i);
            }
            
            if (iIndex == 1) {
                //Almacenamos provisionalemente lo que viene tras 'if '
                //if (criterion1) ----> if ((criterion1)
                //                          and (
                String sAux = ruleText[0].substring(3);
                ruleText[0] = "if (" + sAux;
                
                oRuleSelected.setCombination("and");
                oRuleSelected.getRuleConditions().setConditionCombination("all");
            }
            ruleText[iIndex] = new String(sTAB + "and (");
            
            actTextBox(ruleText);
            oRuleSelected.changeRuleText(ruleText);
            actComponents(ouA.getType());
        }
    }//GEN-LAST:event_jButtonANDActionPerformed
        
    private void jButtonValidateRuleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonValidateRuleActionPerformed
        //oRM.addRuleConditions(oRCs);
        oRM.getRule(oRM.iRuleSelected).validate();
        SpecialDialog.showMessageDialog(this, "The rule was validated correctly", "Validated rule",0,JOptionPane.INFORMATION_MESSAGE);
        
        disableAllComponents();
        _ruleListBox.setSelectedIndex(oRM.iRuleSelected);
        jButtonDeleteRule.setEnabled(true);
    }//GEN-LAST:event_jButtonValidateRuleActionPerformed
    
    private void jButtonDeleteRuleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteRuleActionPerformed
        //Preguntamos al usuario si estás seguro
        int iResul=SpecialDialog.showConfirmDialog(this,"Are you sure that you want to delete this rule?","Delete Rule",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (iResul==JOptionPane.YES_OPTION) {
            int iIndexRule = _ruleListBox.getSelectedIndex();
            //Seleccionamos la nueva regla
            if (((DefaultListModel)_ruleListBox.getModel()).getSize()==1) {
                //Sólo queda esta la regla que vamos a borrar
                _ruleListBox.clearSelection();
                //Después de eliminar esta regla ya no habrá
                //más reglas. Por tanto ni se pueden eliminar, ni validar.
                //Miramos también si fue la rule Default para habilitar
                //el boton DefaultRule
                if (oRM.getRule(iIndexRule).getName() == "Default") bDefault = false;
                disableAllComponents();
            } else { //Seleccionamos la nueva regla (la anterior si es posible)
                if (iIndexRule==0) _ruleListBox.setSelectedIndex(1);
                else _ruleListBox.setSelectedIndex(iIndexRule-1);
            }
            //Borramos la regla y los
            //adaptationCriterion creados por esta
//            if ((adaptationCriteria != null) && (oRM.getRule(iIndexRule).getCriteriaUsed() != null)){
//                for (int j=0;j<oRM.getRule(iIndexRule).getCriteriaUsed().size(); j++){
//                    for (int i=0;i<adaptationCriteria.size();i++){
//                        if (adaptationCriteria.get(i) == oRM.getRule(iIndexRule).getCriteriaUsed().get(j))
//                            adaptationCriteria.remove(i);
//                    }
//                }
//            }
            if (oRM.getRule(iIndexRule).getName().equals("Default")) {
                jButtonDefault.setEnabled(true);
                bDefault = false;
            }
            oRM.removeRule(iIndexRule);
            //Borramos la regla de la lista
            ((DefaultListModel)_ruleListBox.getModel()).remove(iIndexRule);
        }
        
    }//GEN-LAST:event_jButtonDeleteRuleActionPerformed
    
    private void jButtonNewRuleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewRuleActionPerformed
        disableAllComponents();
        //oRCs = null;
        //Pedimos el nombre de la nueva regla
        String sName = SpecialDialog.showInputDialog(oFManager,"Write the new name for the rule ","New Rule Name",JOptionPane.QUESTION_MESSAGE);
        if (sName==null) return;
        //Comprobamos si existe
        if (_ruleListBox.getModel().getSize() > 0) {
            if (((DefaultListModel)_ruleListBox.getModel()).contains(sName)) {
                java.awt.Toolkit.getDefaultToolkit().beep();
                SpecialDialog.showMessageDialog(this,"ERROR: This name is already in use.","ERROR",0,JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        //Comprobamos si es un nombre válido
        if ((sName.equals(""))||(sName.equals("Default"))) {
            java.awt.Toolkit.getDefaultToolkit().beep();
            SpecialDialog.showMessageDialog(this,"ERROR: Invalid name.","ERROR",0,JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        DefaultListModel oModel = new DefaultListModel();
        String[] ruleText = new String[1];
        ruleText[0] = "if (";
        Rule oRuleSelected = new Rule(sName,false,null,ruleText,null,null,oModelAct,oActivities);
        
        actTextBox(ruleText);
        int iIndex;
        if (_ruleListBox.getModel().getSize() > 0) {
            oModel = (DefaultListModel)_ruleListBox.getModel();
            if (oModel.contains("Default")) {
                //Justo antes de la RuleDefault
                iIndex = oModel.size()-1;
                oRM.addRule(oRuleSelected, iIndex);
                oRM.iRuleSelected = iIndex;
                oModel.add(iIndex, sName);
            } else {
                //De última
                oRM.addRule(oRuleSelected);
                oModel.addElement(sName);
                iIndex = oModel.size()-1;
                oRM.iRuleSelected = iIndex;
            }
        } else {
            //De última/primera
            oRM.addRule(oRuleSelected);
            oModel.addElement(sName);
            iIndex = oModel.size()-1;
            oRM.iRuleSelected = iIndex;
        }
        
        _ruleListBox.setModel(oModel);
        //La seleccionamos
        _ruleListBox.setSelectedIndex(iIndex);
        //_ruleListBox.setCellRenderer(new RuleListRenderer());
        
        //This indicates that we are working whit criteria
        inAction = false;
        
        jButtonNewRule.setEnabled(true);
        if (bDefault) jButtonDefault.setEnabled(false);
        else jButtonDefault.setEnabled(true);
        jButtonDeleteRule.setEnabled(true);
        jCBParameter.setEnabled(true);
    }//GEN-LAST:event_jButtonNewRuleActionPerformed
    
    private void jButtonDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDefaultActionPerformed
        // Create the Default rule
        DefaultListModel oModel = new DefaultListModel();
        if(_ruleListBox.getModel().getSize() != 0)
            oModel = (DefaultListModel)_ruleListBox.getModel();
        
        oModel.addElement("Default");
        _ruleListBox.setModel(oModel);
        //_ruleListBox.setCellRenderer(new RuleListRenderer());
        
        createDefaultRule(oModel.size()-1);
    }//GEN-LAST:event_jButtonDefaultActionPerformed
    
    private void _ruleListBoxValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event__ruleListBoxValueChanged
// TODO add your handling code here:
    }//GEN-LAST:event__ruleListBoxValueChanged
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run(){
                try {
                    boolean bVacio;
                    //Falta hacer que nos pasen el árbol JDOM por parametro
                    
                    //Para probar PRUEBA1
                    //Element oElFather = paraProbar(1);
                    
                    //Para probar PRUEBA2
                    //Element oElFather = paraProbar(2);
                    
                    //Para probar INTRODUCIENDO POR PANTALLA EL NOMBRE DEL ARCHIVO .XML
                    Element oElFather = paraProbar();
                    if (oElFather.getChild("adaptation") == null) bVacio = true;
                    else bVacio = false;
                    
                    //new AdaptiveRules_EditorDialog(new javax.swing.JFrame(), bVacio, oElFather,null).setVisible(true);
                } catch (HeadlessException ex) {
                    ex.printStackTrace();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
    
    /**
     * Deshabilita todos los componentes del asistente (excepto el botón Nueva
     * y el botón Finalizar)
     */
    private void disableAllComponents() {
        
        jButtonFinish.setEnabled(true);
        jButtonNewRule.setEnabled(true);
        if (bDefault) jButtonDefault.setEnabled(false);
        else jButtonDefault.setEnabled(true);
        _ruleListBox.setEnabled(true);
        
        if (_ruleListBox.getSelectedIndex() == -1) jButtonDeleteRule.setEnabled(false);
        else jButtonDeleteRule.setEnabled(true);  //Botón de borrar regla
        jButtonValidateRule.setEnabled(false);    //Botón de validar
        
        jButtonDone.setEnabled(false);  //Botón DONE
        jButtonBack.setEnabled(false);   //Botón de deshacer
        jButtonSelect.setEnabled(false);   //Boton select/show
        jButtonSelect.setText("SELECT");
        jSpinnerSelect.setEnabled(false);
        
        jButtonCreate.setEnabled(false);   //Boton Create
        jCBParameter.setEnabled(false);   //ComboBox de seleccion parametro
        jCBParameter.setSelectedIndex(-1);
        jCBOperator.setVisible(false);    //ComboBox de seleccion de operador
        if (jCBOperator.getModel().getSize() > 0) jCBOperator.setSelectedIndex(0);
        jCBValue.setVisible(false);       //ComboBox de seleccion de valor
        if (jCBValue.getModel().getSize() > 0) jCBOperator.setSelectedIndex(0);
        jLabelOperator.setVisible(false);
        jLabelValue.setVisible(false);
        
        _ruleActionList.setEnabled(false);
        _ruleActionList.setSelectedIndex(-1);
        
        jButtonAND.setEnabled(false);   //Boton AND action
        jButtonOR.setEnabled(false);   //Boton OR action
        jButtonXOR.setEnabled(false);   //Boton XOR action
        jButtonNOT.setEnabled(false);    //Botón del NOT
        
        jTALogicalExpr.setText(null);      //Area para la expresión lógica
        jCBComplex.setVisible(false);
        jCBComplexValue.setVisible(false);
        jLabelPoint.setVisible(false);
    }
    
    public void createDefaultRule(int iIndex) {
        
        bDefault = true;
        String[] ruleText = {"else //Default option"};
        Rule oRuleSelected = new Rule("Default",false,null,ruleText,null,null,oModelAct,oActivities);
        oRM.addRule(oRuleSelected);
        oRM.iRuleSelected = iIndex;
        
        //This indicates that we are working whit activities (no criteria)
        inAction = true;
        //Seleccionamos la nueva regla en _ruleListBox
        _ruleListBox.setSelectedIndex(iIndex);
        
        //hasta que se termine no se puede seguir con las demás
        jButtonDeleteRule.setEnabled(true);
        jButtonDefault.setEnabled(false);
        jButtonNewRule.setEnabled(true);
        _ruleActionList.setEnabled(true);
        
        //Seleccionamos todo en el _ruleActionList
        int[] oIndices = new int[oModelAct.size()];
        for (int i=0; i<oModelAct.size(); i++) {
            oIndices[i] = i;
        }
        _ruleActionList.setSelectedIndices(oIndices);
        //_ruleActionList.setCellRenderer(new RuleActionRenderer());
        _ruleActionList.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent oE) {
                actionSelected(oE);
            }
        });
        
        // Mostramos los elementos que se pueden usar
        jButtonSelect.setEnabled(true);
        jSpinnerSelect.setEnabled(true);
        //-1 porque no tiene sentido Select x/x
        jSpinnerSelect.setModel(new SpinnerNumberModel(1,1,oIndices.length-1,1));
        jButtonAND.setEnabled(true);
        jButtonOR.setEnabled(true);
        jButtonXOR.setEnabled(true);
        
        //Actualizamos el cuadro de texto
        actTextBox(ruleText);
    }
    
    public void actTextBox(String[] oLineas){
        
        if ((oLineas != null) || (oLineas.length == 0)) {
            jTALogicalExpr.setText("");
            for (int i=0; i<oLineas.length; i++) jTALogicalExpr.append(oLineas[i]+"\n");
        }
    }
    
    /**
     * Método llamado cuando el usuario hace doble click sobre el Jlist
     * de reglas. Permite editar el nombre de la regla en el JList
     */
    public void mouse(MouseEvent oEvt) {
        int iClosestIndex = _ruleListBox.locationToIndex(oEvt.getPoint());
        if (iClosestIndex!=-1) {
            // iClosestIndex is the nearest index
            //Debemos comprobar si el punto cae dentro del elemento correpondiente al índice
            //Y si no es la regla Default
            if ((_ruleListBox.getCellBounds(iClosestIndex,iClosestIndex).contains(oEvt.getPoint()))
            && (oRM.getRule(iClosestIndex).getName()!="Default")) {
                //Podemos editar el nombre del elemento del JList
                String sNuevo = SpecialDialog.showInputDialog(this,"Write the new name for the rule "+_ruleListBox.getSelectedValue().toString(),"New Rule Name",JOptionPane.QUESTION_MESSAGE);
                if (sNuevo==null) return;
                if (((DefaultListModel)_ruleListBox.getModel()).contains(sNuevo)) {
                    java.awt.Toolkit.getDefaultToolkit().beep();
                    SpecialDialog.showMessageDialog(this,"ERROR: This name is already in use.","ERROR",0,JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if (sNuevo.equals("")) {
                    java.awt.Toolkit.getDefaultToolkit().beep();
                    SpecialDialog.showMessageDialog(this,"ERROR: Invalid name.","ERROR",0,JOptionPane.ERROR_MESSAGE);
                    return;
                }
                ((DefaultListModel)_ruleListBox.getModel()).set(iClosestIndex,sNuevo);
            }
            
        }
    }
    
    /**
     * This function is called when the user
     * select a rule in the _ruleListBox
     *
     * @param oE ListSelectionEvent object
     */
    private void ruleSelected(ListSelectionEvent oE) {
        
        disableAllComponents();
        if (oE.getValueIsAdjusting()) return;
        //Cargamos la regla
        int iIndex;
        if ((iIndex=_ruleListBox.getSelectedIndex())==-1) return;
        
        Rule oRuleSelected = oRM.getRule(iIndex);
        oRM.iRuleSelected = iIndex;
        
        String[] ruleText = oRuleSelected.getRuleText();
        
        if (ruleText != null) {
            actTextBox(ruleText);
        }
        
        //Cuando una regla se encuentra seleccionada
        //se puede borrar, validar y seleccionar su opción asociada
        jButtonDeleteRule.setEnabled(true);
        if (!bDefault) jButtonDefault.setEnabled(true);
        
        if (!oRuleSelected.getValid()) {
            //La regla no fue terminada en su momento
            if (oRuleSelected.getUserActionsSize() == 0) {
                //La ultima accion fue:
                //O se pulsó new Rule o se tecleó default Rule
                if (oRuleSelected.getName().equals("Default")) {
                    //DEfault
                    jButtonDeleteRule.setEnabled(true);
                    jButtonDefault.setEnabled(false);
                    jButtonNewRule.setEnabled(true);
                    _ruleActionList.setEnabled(true);
                    
                    //Seleccionamos todo en el _ruleActionList
                    int[] oIndices = new int[oModelAct.size()];
                    for (int i=0; i<oModelAct.size(); i++) {
                        oIndices[i] = i;
                    }
                    _ruleActionList.setSelectedIndices(oIndices);
                    //_ruleActionList.setCellRenderer(new RuleActionRenderer());
                    _ruleActionList.addListSelectionListener(new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent oE) {
                            actionSelected(oE);
                        }
                    });
                    
                    // Mostramos los elementos que se pueden usar
                    jButtonSelect.setEnabled(true);
                    jSpinnerSelect.setEnabled(true);
                    //-1 porque no tiene sentido Select x/x
                    jSpinnerSelect.setModel(new SpinnerNumberModel(1,1,oIndices.length-1,1));
                    jButtonAND.setEnabled(true);
                    jButtonOR.setEnabled(true);
                    jButtonXOR.setEnabled(true);
                } else {
                    //NewRule
                    jButtonNewRule.setEnabled(true);
                    if (bDefault) jButtonDefault.setEnabled(false);
                    else jButtonDefault.setEnabled(true);
                    jButtonDeleteRule.setEnabled(true);
                    jCBParameter.setEnabled(true);
                }
            } else {
                //Fue cualquier cosa menos lo anterior
                //Tomamos la ultima accion almacenada
                userAction ouA = oRuleSelected.popUserAction();
                if ((ouA.getType() == userAction.DONE) ||
                        (ouA.getType() == userAction.SHOW) ||
                        (ouA.getType() == userAction.SELECT))
                    inAction = true;
                else inAction = false;
                //La volvemos a guardar
                oRuleSelected.pushUserAction(ouA);
                //Actualizamos el estado
                jButtonDeleteRule.setEnabled(true);
                jButtonNewRule.setEnabled(true);
                if (bDefault) jButtonDefault.setEnabled(false);
                else jButtonDefault.setEnabled(true);
                actComponents(ouA.getType());
            }
        }
    }
    
    /**
     * This function is called when the user
     * changes the selection in the _ruleActionList
     *
     * @param oE ListSelectionEvent object
     */
    private void actionSelected(ListSelectionEvent oE) {
        
        if (oE.getValueIsAdjusting()) return;
        
        int[] oIndices;
        
        oIndices=_ruleActionList.getSelectedIndices();
        if (oIndices.length == 0) {
            jButtonSelect.setEnabled(false);
            jSpinnerSelect.setEnabled(false);
            jButtonAND.setEnabled(false);
            jButtonOR.setEnabled(false);
            jButtonNOT.setEnabled(false);
            jButtonXOR.setEnabled(false);
        } else if (oIndices.length == 1){
            jButtonSelect.setText(" SHOW ");
            jButtonSelect.setEnabled(true);
            jSpinnerSelect.setEnabled(false);
            jButtonNOT.setEnabled(true);
            jButtonAND.setEnabled(false);
            jButtonOR.setEnabled(false);
            jButtonXOR.setEnabled(false);
        } else{
            jSpinnerSelect.setModel(new SpinnerNumberModel(1,1,oIndices.length-1,1));
            jSpinnerSelect.setEnabled(true);
            jButtonSelect.setEnabled(true);
            jButtonSelect.setText("SELECT");
            jButtonAND.setEnabled(true);
            jButtonOR.setEnabled(true);
            jButtonXOR.setEnabled(true);
            jButtonNOT.setEnabled(false);
        }
    }
    
    /**
     * This function actualizes the state of the graphicall components
     *
     * @param iCase int The type of the last user action 
     */
    public void actComponents(int iCase){
        
        switch (iCase){
            case userAction.ANDACT:
            case userAction.XORACT:
            case userAction.ORACT:
                jButtonAND.setEnabled(false);
                //jButtonBack.setEnabled(true);
                jButtonBack.setEnabled(false);
                jButtonNOT.setEnabled(true);
                jButtonOR.setEnabled(false);
                jButtonSelect.setText(" SHOW ");
                jButtonSelect.setEnabled(true);
                jButtonXOR.setEnabled(false);
                jSpinnerSelect.setEnabled(false);
                break;
            case userAction.NOTACT:
                jButtonAND.setEnabled(false);
                //jButtonBack.setEnabled(true);
                jButtonBack.setEnabled(false);
                if (_ruleActionList.getSelectedIndices().length > 1) jButtonNOT.setEnabled(false);
                else jButtonNOT.setEnabled(true);
                jButtonOR.setEnabled(false);
                jButtonSelect.setText(" SHOW ");
                jButtonSelect.setEnabled(true);
                jButtonXOR.setEnabled(false);
                jSpinnerSelect.setEnabled(false);
                break;
            case userAction.DONE:
                // Mostramos los elementos que se pueden usar
                jButtonSelect.setEnabled(true);
                jSpinnerSelect.setEnabled(true);
                jButtonAND.setEnabled(true);
                jButtonOR.setEnabled(true);
                jButtonXOR.setEnabled(true);
                jButtonBack.setEnabled(true);
                //Si es mayor que uno (estan todos seleccionados)
                //no podemos habilitar NOT
                if (oModelAct.size() > 1) jButtonNOT.setEnabled(false);
                else jButtonNOT.setEnabled(true);
                jCBParameter.setEnabled(false);
                jCBParameter.setSelectedIndex(-1);
                jCBOperator.setVisible(false);
                jCBValue.setVisible(false);
                jLabelOperator.setVisible(false);
                jLabelValue.setVisible(false);
                jButtonCreate.setEnabled(false);
                jButtonDone.setEnabled(false);
                _ruleActionList.setEnabled(true);
                
                if (_ruleActionList.getSelectedIndices().length == 1) {
                    jButtonSelect.setText(" SHOW ");
                    jButtonSelect.setEnabled(true);
                    jSpinnerSelect.setEnabled(false);
                    jButtonAND.setEnabled(false);
                    jButtonOR.setEnabled(false);
                    jButtonXOR.setEnabled(false);
                    jButtonNOT.setEnabled(true);
                }
                break;
            case userAction.ORCRI:
            case userAction.ANDCRI:
                jCBParameter.setEnabled(true);
                jCBParameter.setSelectedIndex(-1);
                jButtonCreate.setEnabled(false);
                jButtonNOT.setEnabled(false);
                jButtonBack.setEnabled(true);
                jButtonDone.setEnabled(false);
                jButtonAND.setEnabled(false);
                jButtonOR.setEnabled(false);
                break;
            case userAction.SHOW:
                jButtonAND.setEnabled(false);
                jButtonBack.setEnabled(true);
                jButtonNOT.setEnabled(false); //esto cambia
                jButtonOR.setEnabled(false);
                jButtonSelect.setText(" SHOW ");
                jButtonSelect.setEnabled(false); //esto cambia
                jButtonXOR.setEnabled(false);
                jSpinnerSelect.setEnabled(false);
                jButtonValidateRule.setEnabled(true);
                _ruleActionList.setEnabled(false);
                break;
            case userAction.SELECT:
                jButtonAND.setEnabled(false);
                //jButtonBack.setEnabled(true);
                jButtonBack.setEnabled(true);
                jButtonNOT.setEnabled(true);
                jButtonOR.setEnabled(false);
                jButtonSelect.setText(" SHOW ");
                jButtonSelect.setEnabled(true);
                jButtonXOR.setEnabled(false);
                jSpinnerSelect.setEnabled(false);
                break;
            case userAction.CREATE:
                jCBParameter.setEnabled(false);
                jCBParameter.setSelectedIndex(-1);
                jCBOperator.setVisible(false);
                jCBValue.setVisible(false);
                jLabelOperator.setVisible(false);
                jLabelValue.setVisible(false);
                jButtonCreate.setEnabled(false);
                jButtonNOT.setEnabled(true);
                jButtonBack.setEnabled(true);
                jButtonDone.setEnabled(true);
                if (oRM.getRule(oRM.iRuleSelected).getCombination().equals("and")) {
                    jButtonAND.setEnabled(true);
                    jButtonOR.setEnabled(false);
                } else if (oRM.getRule(oRM.iRuleSelected).getCombination().equals("or")) {
                    jButtonOR.setEnabled(true);
                    jButtonAND.setEnabled(false);
                } else {
                    jButtonAND.setEnabled(true);
                    jButtonOR.setEnabled(true);
                }
                break;
            case userAction.CREATECOMPLEX:
                //HELP
                //tenemos un problema!!!
                //Si ya se hizo (a == aa) or (b == bb)
                //Si se crea un nuevo criterio con un parametro complex
                //Se jode todo porque solo puede llevar and's
                
                jCBParameter.setEnabled(false);
                jCBParameter.setSelectedIndex(-1);
                jCBOperator.setVisible(false);
                jCBValue.setVisible(false);
                jCBComplex.setVisible(false);
                jCBComplexValue.setVisible(false);
                jLabelPoint.setVisible(false);
                jLabelOperator.setVisible(false);
                jLabelValue.setVisible(false);
                
                jButtonCreate.setEnabled(false);
                jButtonNOT.setEnabled(true);
                jButtonBack.setEnabled(true);
                jButtonDone.setEnabled(true);
                jButtonAND.setEnabled(true);
                jButtonOR.setEnabled(false);
//                if (oRM.getRule(oRM.iRuleSelected).getCombination().equals("and")) {
//                    jButtonAND.setEnabled(true);
//                    jButtonOR.setEnabled(false);
//                } else if (oRM.getRule(oRM.iRuleSelected).getCombination().equals("or")) {
//                    jButtonOR.setEnabled(true);
//                    jButtonAND.setEnabled(false);
//                } else {
//                    jButtonAND.setEnabled(true);
//                    jButtonOR.setEnabled(true);
//                }
                break;
            case userAction.NOTCRI:
                jButtonNOT.setEnabled(false);
                break;
        }
    }
    
    /**
     * Comprueba si todas las reglas han sido validadas. Pregunta al usuario
     * si esta seguro de cerrar si no han sido todas validadas. Crea el
     * árbol JDOM correpondiente y lo devuelve?. Cierra
     */
    private void close() {
        boolean bValidated = true;
        int[] oIndices = new int[oRM.sizeRules()];
        int a = 0;
        
        for (int i=0;i<oRM.sizeRules();i++) {
            if (!oRM.getRule(i).getValid()) {
                bValidated = false;
                oIndices[a] = i;
                a++;
                break;
            }
        }
        int[] oIndicesNew = new int[a];
        for (int i=0; i<a; i++) oIndicesNew[i] = oIndices[i];
        if (!bValidated) {
            if (SpecialDialog.showConfirmDialog(this,"There are invalidated rules. Do you want to delete these rules?","Close with invalidate rules",JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) return;
            deleteInvalidRules(oIndicesNew);
        }
        
        if (oRM.sizeRules() > 0) {
            //En caso de que queden reglas
        	//System.out.println("Salvamos " + oRM.sizeRules() + " reglas v�lidas.");
        	
        	java.util.List tmpList = oFatherElement.getContent(new ElementFilter("adaptation"));
        	//System.out.println("  (# elementos adaptation (esperados 1): " + tmpList.size());
        	
        	Element oElAdap = (Element) tmpList.get(0); 
            java.util.List aBorrar = oElAdap.getContent(new ElementFilter());
            //System.out.println("  (* elementos a borrar (esperados 2): " + aBorrar.size());
            if (aBorrar.size() > 0) {
            	oElAdap.removeChild("adaptationParameters");
            	oElAdap.removeChild("adaptationRules");
            }        	
        	
//            if (sAdaptationID != null) oElAdap.setAttribute("ID",sAdaptationID);
//            if (sAdaptationIDRef != null) oElAdap.setAttribute("IDRef",sAdaptationIDRef);
            Element oElAC = new Element("adaptationParameters");
            ArrayList<adaptationCriterion> oACInc = new ArrayList<adaptationCriterion>();
            for (int h=0; h<oRM.sizeRules();h++){
                Rule oRuleSelected = oRM.getRule(h);
                if (!(oRuleSelected.getName().equals("Default"))) {
                    for (int i=0; i<oRuleSelected.getCriteriaUsed().size(); i++) {
                        boolean bExists = false;
                        for (int j=0; j<oACInc.size(); j++) {
                            //Miramos si ya fue incluido
                            if ((oACInc.get(j).getSource().equals(oRuleSelected.getCriteriaUsed().get(i).getSource())) &&
                                    (oACInc.get(j).getValue().equals(oRuleSelected.getCriteriaUsed().get(i).getValue())))
                                bExists = true;
                        }
                        if (!bExists) {
                            oACInc.add(oRuleSelected.getCriteriaUsed().get(i));
                            Element oEl = oRuleSelected.getCriteriaUsed().get(i).getElement();
                            oElAC.addContent(oEl);
                        }
                    }
                }
            }
            oElAdap.addContent(oElAC);
            
            Element oElRC =  new Element("adaptationRules");
            for (int i=0; i<oRM.sizeRules(); i++) {
                oElRC.addContent(oRM.getRule(i).getElement());
            }
            oElAdap.addContent(oElRC);

/*            oFatherElement.addContent(oElAdap);
            oFatherElement.removeContent(oElAdapOriginal); */
            
            
            
            cp.changedElement(this, oFatherElement);
        }
  
        //paraProbarPrintAdaptation(oFatherElement);
        //HACER

        dispose();
    }
    
    /**
     * Deletes the rules that indicates the input variable oIndices
     *
     * @param oIndices int[]
     */
    public void deleteInvalidRules(int[] oIndices){
        
        for (int i = 0; i<oIndices.length; i++) {
            if (oRM.getRule(oIndices[i]).getName() == "Default") bDefault = false;
            oRM.removeRule(oIndices[i]);
        }
    }
    
    /**
     * Counts the integer value of a "numeric string"
     *
     * @param sValue The String
     * @return The Non-negative integer value or -1 if the String is not numeric only
     */
    public Integer StringToInteger(String sValue) {
        int iValue = 0;
        int iCard = 1;
        
        char[] oValue = sValue.toCharArray();
        for (int i = sValue.length()-1; i>=0; i--){
            int aux;
            switch (oValue[i]){
                case '0':
                    aux=0;
                    break;
                case '1':
                    aux=1;
                    break;
                case '2':
                    aux=2;
                    break;
                case '3':
                    aux=3;
                    break;
                case '4':
                    aux=4;
                    break;
                case '5':
                    aux=5;
                    break;
                case '6':
                    aux=6;
                    break;
                case '7':
                    aux=7;
                    break;
                case '8':
                    aux=8;
                    break;
                case '9':
                    aux=9;
                    break;
                default:
                    return -1;
            }
            iValue += aux * iCard;
            iCard = iCard * 10;
        }
        return iValue;
    }
    
    public static Element paraProbar(int iType) throws Exception{
        
        try {
            SAXBuilder builder=new SAXBuilder(false);
            //usar el parser Xerces y no queremos
            //que valide el documento
            Document oDoc = null;
            
            if (iType == 1) oDoc = builder.build("prueba1.xml");
            else if (iType == 2) oDoc = builder.build("prueba2.xml");
            Element oRaiz = oDoc.getRootElement();
            
            return oRaiz;
            
        } catch(Exception oE) {
            oE.printStackTrace();
            java.awt.Toolkit.getDefaultToolkit().beep();
            //SpecialDialog.showMessageDialog(this,oE.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
            System.exit(-1);
            return null;
        }
        
    }
    
    public static void paraProbarPrintAdaptation(Element raiz){
        Element oRaiz = (Element) raiz.clone();
        
        //Creamos el documento
        Document doc = new Document(oRaiz);
        
        //Vamos a almacenarlo en un fichero y ademas lo sacaremos por pantalla
        try{
            XMLOutputter out = new XMLOutputter();
            FileOutputStream file = new FileOutputStream("prueba_result.xml");
            out.output(doc,file);
            file.flush();
            file.close();
            //out.output(doc,System.out);  //Esto es para sacarlo por pantalla
        }catch(Exception e){e.printStackTrace();}
        
    }
    
    public static Element paraProbar() throws Exception{
        
        try {
            SAXBuilder builder=new SAXBuilder(false);
            //usar el parser Xerces y no queremos
            //que valide el documento
            Document oDoc = null;
            String sName;
            
            //The file must be in the project dir
            
            sName = SpecialDialog.showInputDialog(oFManager,"Set the name of the file .xml to try.","File input dialog",javax.swing.JOptionPane.OK_OPTION);
            
            File oFile = new File(sName);
           // System.out.println(System.getProperties().getProperty("user.dir"));
           // System.out.println(System.getProperties().getProperty("java.class.path"));
            oDoc = builder.build(oFile);
            
            Element oRaiz = oDoc.getRootElement();
            
            return oRaiz;
            
        } catch(Exception oE) {
            oE.printStackTrace();
            java.awt.Toolkit.getDefaultToolkit().beep();
            //SpecialDialog.showMessageDialog(this,oE.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
            System.exit(-1);
            return null;
        }
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane _actionRuleList;
    private javax.swing.JList _ruleActionList;
    private javax.swing.JList _ruleListBox;
    private javax.swing.JButton jButtonAND;
    private javax.swing.JButton jButtonBack;
    private javax.swing.JButton jButtonCreate;
    private javax.swing.JButton jButtonDefault;
    private javax.swing.JButton jButtonDeleteRule;
    private javax.swing.JButton jButtonDone;
    private javax.swing.JButton jButtonFinish;
    private javax.swing.JButton jButtonNOT;
    private javax.swing.JButton jButtonNewRule;
    private javax.swing.JButton jButtonOR;
    private javax.swing.JButton jButtonSelect;
    private javax.swing.JButton jButtonValidateRule;
    private javax.swing.JButton jButtonXOR;
    private javax.swing.JComboBox jCBComplex;
    private javax.swing.JComboBox jCBComplexValue;
    private javax.swing.JComboBox jCBOperator;
    private javax.swing.JComboBox jCBParameter;
    private javax.swing.JComboBox jCBValue;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelOperator;
    private javax.swing.JLabel jLabelPoint;
    private javax.swing.JLabel jLabelValue;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSpinner jSpinnerSelect;
    private javax.swing.JTextArea jTALogicalExpr;
    // End of variables declaration//GEN-END:variables
    
}


