package tmaestroplayer.template;

import java.awt.Component;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.xpath.*;

public abstract class TemplateComponentsJavaXML extends TemplateComponentsXML {

    /**
     * Hilos de los componentes con temporizacion
     */
    public static Vector HILOS = new Vector();
    public static boolean NEXT = false;
    public static int newfocused = -1;

    public TemplateComponentsJavaXML(String xmlfilename) {
        super(xmlfilename);
    }

    /**
     * Lectura del fichero TemplateComponents.xml
     **/
    protected TemplateComponent initTemplateComponents(String xmlfilename) {

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            Element e = doc.getDocumentElement();
            NodeList doclist = e.getChildNodes();
            for (int i = 0; i < doclist.getLength(); i++) {
                Node maincomponentnode = e.getChildNodes().item(i);
                if (getStringAttribute(maincomponentnode, "type") != null) {
                    return initTemplateComponent(maincomponentnode);
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Lectura de un nodo del fichero TemplateComponents.xml
     **/
    private TemplateComponent initTemplateComponent(Node xmlnode) {

        // Init component
        String componentClass = getStringAttribute(xmlnode, "type");
        String componentName = getStringAttribute(xmlnode, "componentName");

        int x = getIntAttribute(xmlnode, "x", TemplateComponent.X_DEFAULT);
        int y = getIntAttribute(xmlnode, "y", TemplateComponent.Y_DEFAULT);
        int z = getIntAttribute(xmlnode, "z", TemplateComponent.Z_DEFAULT);
        int w = getIntAttribute(xmlnode, "w", TemplateComponent.W_DEFAULT);
        int h = getIntAttribute(xmlnode, "h", TemplateComponent.H_DEFAULT);

        TemplateComponent tc = new TemplateComponent(componentClass, componentName, x, y, z, w, h);


        // Init children
        NodeList xmlnodechildren = xmlnode.getChildNodes();
        for (int i = 0; i < xmlnodechildren.getLength(); i++) {
            Node snode = xmlnodechildren.item(i);
            if (getStringAttribute(snode, "type") != null) {
                tc.containedcomponents.add(initTemplateComponent(snode));
            }
        }
        // Return component
        return tc;
    }

    /**
     * Función que convierte a Int el valor de un nodo dado
     **/
    private static int getIntAttribute(Node xmlnode, String attributeName, int defaultvalue) {
        try {
            return new Integer(xmlnode.getAttributes().getNamedItem(attributeName).getTextContent()).intValue();
        } catch (Exception e) {
            return defaultvalue;
        }
    }

    /**
     * Función que convierte a String el valor de un nodo dado
     **/
    private static String getStringAttribute(Node xmlnode, String attributeName) {
        try {
            return xmlnode.getAttributes().getNamedItem(attributeName).getTextContent();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Retorna el nombre del boton referenciado en el fichero NextButton.xml
     **/
    public String getNextButton(String xmlfilename) {

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            Node nodo = (Node) xpath.evaluate(
                    "//nextButton/component[@componentName]", doc,
                    XPathConstants.NODE);
            return (nodo.getAttributes().getNamedItem("componentName").getTextContent());
        } catch (Exception e) {
            System.out.println("WARNING:seguramente no existe el next");
            //e.printStackTrace();
            return null;
        }
    }

    /**
     * Retorna el nombre del botón referenciado en el fichero ExitButton.xml
     **/
    public String getExitButton(String xmlfilename) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            Node nodo = (Node) xpath.evaluate("//exitButton/component[@componentName]", doc, XPathConstants.NODE);
            return (nodo.getAttributes().getNamedItem("componentName").getTextContent());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Lectura del fichero xml de las preguntas de Test
     * @param xmlfilename: test.xml
     * @param asocTest: contiene las relaciones {key,value} {idAnswer, nombreButton nombreLabel nombreReproductor}
     * @param playersTest: contiene los nombres de los reproductores playerQuestion,playerRight,playerWrong,playerInactivity,questionButton
     * @return número de posibles respuestas 
     **/
    public int readTest(String xmlfilename, HashMap asocTest, Vector playersTest) {
        Vector answerTrue = new Vector();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaAnswers = (NodeList) xpath.evaluate("//test/testQuestion/*", doc, XPathConstants.NODESET);
            int num = listaAnswers.getLength();
            if (num == 0) {
                return 0;
            }
            for (int i = 0; i < num; i++) {
                Node ValuesComponents = listaAnswers.item(i);
                if (ValuesComponents != null) {
                    String nameState = ValuesComponents.getNodeName();
                    //SSS 26102009 esta comprobacion no estaba, pero debe ser necesaria
                    if (ValuesComponents.getAttributes().getNamedItem("componentName") != null) {
                        if (nameState.equals("playerQuestion")) {
                            playersTest.add(ValuesComponents.getAttributes().getNamedItem("componentName").getTextContent());
                        } else if (nameState.equals("playerRight")) {
                            playersTest.add(ValuesComponents.getAttributes().getNamedItem("componentName").getTextContent());
                        } else if (nameState.equals("playerWrong")) {
                            playersTest.add(ValuesComponents.getAttributes().getNamedItem("componentName").getTextContent());
                        } else if (nameState.equals("playerInactivity")) {
                            playersTest.add(ValuesComponents.getAttributes().getNamedItem("componentName").getTextContent());
                        } else if (nameState.equals("questionButton")) {
                            playersTest.add(ValuesComponents.getAttributes().getNamedItem("componentName").getTextContent());
                        }
                    }
                    NodeList listcmp = ValuesComponents.getChildNodes();
                    String button = "";
                    String label = "";
                    String player = "";
                    boolean typeAnswer = false;
                    //SSS 26102009 aqui cambio el for, debí corregirlo...
                    // for (int j = 0; j < num; j++) { // Se trata de tipo answer
                    for (int j = 0; j < listcmp.getLength(); j++) { // Se trata de tipo answer

                        Node value = listcmp.item(j);
                        if (value != null) {
                            typeAnswer = true;
                            if (value.getNodeName().equals("button")) {
                                //SSS 26102009 esto no estaba, debe ser correccion
                                if (value.getAttributes().getNamedItem("componentName") != null) {
                                    button = value.getAttributes().getNamedItem("componentName").getTextContent();
                                }
                            } else if (value.getNodeName().equals("label")) {
                                //SSS 26102009 esto no estaba, debe ser correccion
                                if (value.getAttributes().getNamedItem("componentName") != null) {
                                    label = value.getAttributes().getNamedItem("componentName").getTextContent();
                                }
                            } else if (value.getNodeName().equals("player")) {
                                //SSS 26102009 esto no estaba, debe ser correccion
                                if (value.getAttributes().getNamedItem("componentName") != null) {
                                    player = value.getAttributes().getNamedItem("componentName").getTextContent();
                                }
                            }

                        }
                    }
                    if (typeAnswer) {
                        typeAnswer = false;
                        int id = Integer.parseInt(ValuesComponents.getAttributes().getNamedItem("id").getTextContent());
                        String asoc = button + " " + label + " " + player;
                        asocTest.put(id, asoc);
                        if (ValuesComponents.getAttributes().getNamedItem("isTrue").getTextContent().equals("true")) {
                            answerTrue.add(id);
                        }
                    }
                }
            }
            if (asocTest.size() > 0) {
                asocTest.put("answerTrue", answerTrue);
            }
            //SSS 26102009 aqui devuelvo otra cosa...
            return Integer.parseInt(answerTrue.get(0).toString());
            //return asocTest.size();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    public int readTestNew(String xmlfilename, HashMap<String, HashMap<String, String>> asocTest, HashMap<String, String> playersTest) {

        return 0;
    }

    /**
     * Lectura del fichero xml de controles de reproductores
     * @param xmlfilename: MediaPlayersControl.xml
     * @param name: nombre del reproductor 
     * @return nombre del botón de play
     **/
    public String getPlayButton(String xmlfilename, String name) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaPlayers = (NodeList) xpath.evaluate("//mediaPlayersControl/component[@componentName]", doc, XPathConstants.NODESET);
            int num = listaPlayers.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node player = listaPlayers.item(i);
                String namePlayer = player.getAttributes().getNamedItem("componentName").getTextContent();
                if (namePlayer.equals(name)) {
                    Node play = (Node) xpath.evaluate("//mediaPlayersControl/component/play", player, XPathConstants.NODE);
                    return (play.getAttributes().getNamedItem("componentName").getTextContent());
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Lectura del fichero xml de controles de reproductores
     * @param xmlfilename: MediaPlayersControl.xml
     * @param name: nombre del reproductor 
     * @return valor del campo autoplay (true o false)
     **/
    public String getAutoplay(String xmlfilename, String name) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaPlayers = (NodeList) xpath.evaluate("//mediaPlayersControl/component[@autoplay]", doc, XPathConstants.NODESET);
            int num = listaPlayers.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node player = listaPlayers.item(i);
                String namePlayer = player.getAttributes().getNamedItem("componentName").getTextContent();
                if (namePlayer.equals(name)) {
                    return (player.getAttributes().getNamedItem("autoplay").getTextContent());
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Lectura del fichero xml de controles de reproductores
     * @param xmlfilename: MediaPlayersControl.xml
     * @param name: nombre del reproductor 
     * @return nombre del botón de stop
     **/
    public String getStopButton(String xmlfilename, String name) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaPlayers = (NodeList) xpath.evaluate("//mediaPlayersControl/component[@componentName]", doc, XPathConstants.NODESET);
            int num = listaPlayers.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node player = listaPlayers.item(i);
                String namePlayer = player.getAttributes().getNamedItem("componentName").getTextContent();
                if (namePlayer.equals(name)) {
                    Node stop = (Node) xpath.evaluate("//mediaPlayersControl/component/stop", player, XPathConstants.NODE);
                    return (stop.getAttributes().getNamedItem("componentName").getTextContent());
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Lectura del fichero xml de controles de reproductores
     * @param xmlfilename: MediaPlayersControl.xml
     * @param name: nombre del reproductor 
     * @return nombre del botón de pause
     **/
    public String getPauseButton(String xmlfilename, String name) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaPlayers = (NodeList) xpath.evaluate("//mediaPlayersControl/component[@componentName]", doc, XPathConstants.NODESET);
            int num = listaPlayers.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node player = listaPlayers.item(i);
                String namePlayer = player.getAttributes().getNamedItem("componentName").getTextContent();
                if (namePlayer.equals(name)) {
                    Node pause = (Node) xpath.evaluate("//mediaPlayersControl/component/pause", player, XPathConstants.NODE);
                    return (pause.getAttributes().getNamedItem("componentName").getTextContent());
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Lectura del fichero xml de controles de reproductores
     * @param xmlfilename: MediaPlayersControl.xml
     * @return lista {key,value} donde {playnameButton, nameMediaPlayer},{stopnameButton, nameMediaPlayer},{pausenameButton, nameMediaPlayer}
     **/
    //SSS 26102009 aqui esta todo mal funcion nueva
    public HashMap getPlayerButtons(String xmlfilename) {

        HashMap resultado = new HashMap();
        Vector buttons = new Vector();
        String nameButton2 = "";
        String nameButton = "";
        String nameButton3 = "";
        String nodeName = "";
        boolean r = false;
        boolean fin = true;
        int index = 0;
        int indexK = 0;
        Vector players = new Vector();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaPlayers = (NodeList) xpath.evaluate("//mediaPlayersControl/component[@componentName]", doc, XPathConstants.NODESET);
            int num = listaPlayers.getLength();
            if (num == 0) {
                return resultado;
            }
            
            //SSS 26102009 cambia estaba mal
            int aux = 0;
            //System.out.println("entro en whilefin " + indexK + " y num vale " + num);
        
            //entro una vez por cada player
            for (int j = 0; j < 4; j++) {
                for (int i = 0; i < num; i++) {
                    Node player = listaPlayers.item(i);
                    String namePlayer = player.getAttributes().getNamedItem("componentName").getTextContent();
                    //namePlayer es el nombre del player (grande o peque)
                    buttons.removeAllElements();
                    int k = i + 1;
                    NodeList listButtons = (NodeList) xpath.evaluate("//mediaPlayersControl/component[" + k + "]/*", player, XPathConstants.NODESET);

                   // System.out.println(listButtons.item(j).getNodeName() + " list buttons " + listButtons.item(j).getAttributes().getNamedItem("componentName").getTextContent());
                    if (listButtons.item(j).getAttributes().getNamedItem("componentName")!=null){
                    String nombreboton = listButtons.item(j).getAttributes().getNamedItem("componentName").getTextContent();
                    String boton = listButtons.item(j).getNodeName();
                    String existe = null;
                    existe = (String) resultado.get(listButtons.item(j).getNodeName() + listButtons.item(j).getAttributes().getNamedItem("componentName").getTextContent());
                    if (existe == null) {
                       // System.out.println("no existe");
                        resultado.put(listButtons.item(j).getNodeName() + listButtons.item(j).getAttributes().getNamedItem("componentName").getTextContent(), namePlayer);
                    } else {
                        //System.out.println("si existe los sustituyo");
                        existe = existe + " " + namePlayer;
                        resultado.remove(listButtons.item(j).getNodeName() + listButtons.item(j).getAttributes().getNamedItem("componentName").getTextContent());
                        resultado.put(listButtons.item(j).getNodeName() + listButtons.item(j).getAttributes().getNamedItem("componentName").getTextContent(), existe);
                    }
                    }
                }

            }
            /*
            System.out.println("Vamos a entrar en el bucle en el que obtenemos los botones");
            System.out.println("numero de reproductores: " + num);
            while (fin) {
                System.out.println("fin: " + fin + " " + num);
                for (int i = 0; i < num; i++) {
                    Node player = listaPlayers.item(i);
                    String namePlayer = player.getAttributes().getNamedItem("componentName").getTextContent();
                    buttons.removeAllElements();
                    int k = i + 1;
                    NodeList listButtons = (NodeList) xpath.evaluate("//mediaPlayersControl/component[" + k + "]/*", player, XPathConstants.NODESET);
                    int numB = listButtons.getLength();
                    for (int j = indexK; j < numB; j++) {
                        Node button = listButtons.item(j);
                        Node n = button.getAttributes().getNamedItem("componentName");
                        if (n != null) {
                            nameButton = n.getTextContent();
                            //nameButton = button.getAttributes().getNamedItem("componentName").getTextContent();
                        }
                        if (nameButton2.equals("")) {
                            nameButton2 = nameButton;
                            nodeName = button.getNodeName();
                            index = j;
                            players.add(namePlayer);
                            nameButton3 = button.getNodeName();
                            break;
                        } else if (nameButton.equals(nameButton2)) {
                            players.add(namePlayer);
                            break;
                        }
                    }
                }
                if (indexK < 4) {
                    indexK = index + 1;
                    String cadena = "";
                    for (int l = 0; l < players.size(); l++) {
                        if (l < players.size() - 1) {
                            cadena = cadena + players.get(l) + " ";
                        } else {
                            cadena = cadena + players.get(l);
                        }
                    }
                    resultado.put(nameButton3 + nameButton2, cadena);
                    String ii = nameButton3 + nameButton2;
                    players.removeAllElements();
                    nameButton2 = "";
                } else {
                    fin = false;
                    //resultado.put(nodeName+nameButton2,namePlayer);
                }
            }
            */
            return resultado;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultado;
    }

    /**
     * Lectura del fichero xml de paneles con desplazamiento
     * @param xmlfilename: ScrollPanelBar.xml
     * @return lista {key,value} donde {horizontalnameBar, nameScrollPanel}, {verticalnameBar,nameScrollPanel}
     **/
    public HashMap getScrollPanel(String xmlfilename, Vector nameScroll) {
        HashMap resultado = new HashMap();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaScrollPanel = (NodeList) xpath.evaluate("//scrollPanelBar/scrollPanel[@componentName]", doc, XPathConstants.NODESET);
            int num = listaScrollPanel.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node ScrollPanel = listaScrollPanel.item(i);
                String nameScrollPanel = ScrollPanel.getAttributes().getNamedItem("componentName").getTextContent();
                int k = i + 1;
                NodeList listBarras = (NodeList) xpath.evaluate("//scrollPanelBar/scrollPanel[" + k + "]/*", ScrollPanel, XPathConstants.NODESET);
                int numB = listBarras.getLength();
                for (int j = 0; j < numB; j++) {
                    Node barra = listBarras.item(j);
                    String nameBarra = barra.getAttributes().getNamedItem("componentName").getTextContent();
                    nameScroll.add(nameScrollPanel);
                    resultado.put(barra.getNodeName() + nameBarra, nameScrollPanel);
                }
            }
            return resultado;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultado;
    }

    /**
     * Lectura del fichero xml de opción de reproducción
     * @param xmlfilename: Option.xml
     * @return elemento principal del documento
     **/
    public Element readOption(String xmlfilename) {
        System.out.println("Fichero de opcion "+xmlfilename);
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            Element e = doc.getDocumentElement();
            return e;
        } catch (ParserConfigurationException e1) {
            e1.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Lectura del fichero xml de opción de reproducción
     * @param e: elemento del documento
     * @param cmpClass: nombre de la clase del componente (ej. para un botón sería com.uvigo.mhp.ui.HButton)
     * @param cmpName: nombre del componente
     * @return lista con las propiedades de cada componente
     **/
    public HashMap readValuesOption(Element e, String cmpClass, String cmpName) {

        HashMap resultado = new HashMap();
        NodeList doclist = e.getChildNodes();
        for (int i = 0; i < doclist.getLength(); i++) {
            Node maincomponentnode = e.getChildNodes().item(i);
            if (maincomponentnode.getNodeName().equals("components")) {
                for (int j = 0; j < maincomponentnode.getChildNodes().getLength(); j++) {
                    Node maincomponentnodes = maincomponentnode.getChildNodes().item(j);
                    if (maincomponentnodes.getNodeName().equals("component")) {
                        String componentClass = getStringAttribute(maincomponentnodes, "componentClass");
                        String componentName = getStringAttribute(maincomponentnodes, "name");
                        if ((componentClass.equals(cmpClass)) && (componentName.equals(cmpName))) {
                            NodeList doclist2 = maincomponentnodes.getChildNodes();
                            for (int k = 0; k < doclist2.getLength(); k++) {
                                Node maincomponentnode2 = maincomponentnodes.getChildNodes().item(k);
                                if (maincomponentnode2.getNodeName().equals("properties")) {
                                    NodeList doclist3 = maincomponentnode2.getChildNodes();
                                    for (int l = 0; l < doclist3.getLength(); l++) {
                                        Node maincomponentnode3 = maincomponentnode2.getChildNodes().item(l);
                                        if (maincomponentnode3.getNodeName().equals("property")) {
                                            NodeList doclist4 = maincomponentnode3.getChildNodes();
                                            String name = "";
                                            String value = "";
                                            String param = "";
                                            int cont = 0;
                                            for (int m = 0; m < doclist4.getLength(); m++) {
                                                Node maincomponentnode4 = maincomponentnode3.getChildNodes().item(m);
                                                if (maincomponentnode4.getNodeName().equals("name")) {
                                                    name = maincomponentnode4.getTextContent();
                                                }
                                                if (maincomponentnode4.getNodeName().equals("param")) {
                                                    cont++;
                                                    if (param != "") {
                                                        param = param + " " + maincomponentnode4.getTextContent();
                                                    } else {
                                                        param = maincomponentnode4.getTextContent();
                                                    }
                                                }
                                                if (maincomponentnode4.getNodeName().equals("value")) {
                                                    value = maincomponentnode4.getTextContent();
                                                }
                                                if ((name != "") && (value != "")) {
                                                    resultado.put(name, value);
                                                    name = "";
                                                    value = "";
                                                } else if ((name != "") && (cont == 3)) {
                                                    resultado.put(name, param);
                                                    name = "";
                                                    value = "";
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            
                            return resultado;
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * Lectura del fichero xml que figura en la propiedad contentFile o configurationFile de los elementos
     * com.uvigo.mhp.ui.HButton y com.uvigo.mhp.ui.HSwitch.
     * @param xmlfilename: nombre del fichero xml
     * @return lista con las propiedades que figuran en el fichero xml
     **/
    public HashMap readValuesComponents(String xmlfilename) {

        HashMap resultado = new HashMap();

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaValuesComponents = (NodeList) xpath.evaluate("//contentList/*", doc, XPathConstants.NODESET);
            int num = listaValuesComponents.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node ValuesComponents = listaValuesComponents.item(i);
                String nameState = ValuesComponents.getNodeName();
                if (nameState.endsWith("StateContent")) {
                    NodeList listaStateContent = (NodeList) xpath.evaluate("//contentList/" + nameState + "/*", doc, XPathConstants.NODESET);
                    HashMap propiedades = new HashMap();
                    int numS = listaStateContent.getLength();
                    if (numS == 0) {
                        return null;
                    }
                    for (int j = 0; j < numS; j++) {
                        Node StateContent = listaStateContent.item(j);
                        String nameStates = StateContent.getNodeName();
                        if (nameStates.equals("graphicContent")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                        if (nameStates.equals("textContent")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                    }
                    if (numS > 0) {
                        resultado.put(nameState, propiedades);
                    }
                }
            }
        } catch (XPathExpressionException e1) {
            e1.printStackTrace();
        } catch (ParserConfigurationException e2) {
            e2.printStackTrace();
        } catch (SAXException e3) {
            e3.printStackTrace();
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        return resultado;
    }

    /**
     * Lectura del fichero xml que figura en la propiedad configurationFile del elemento com.uvigo.mhp.ui.HMenu
     * @param xmlfilename: nombre del fichero xml
     * @return lista con las propiedades que figuran en el fichero xml
     **/
    public HashMap readValuesComponentsMenu(String xmlfilename) {

        HashMap resultado = new HashMap();

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaValuesComponents = (NodeList) xpath.evaluate("//menu/*", doc, XPathConstants.NODESET);
            int num = listaValuesComponents.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node ValuesComponents = listaValuesComponents.item(i);
                String nameState = ValuesComponents.getNodeName();
                if (nameState.equals("menuElement")) {
                    NodeList listaStateContent = ValuesComponents.getChildNodes();
                    HashMap propiedades = new HashMap();
                    int numS = listaStateContent.getLength();
                    if (numS == 0) {
                        return null;
                    }
                    for (int j = 0; j < numS; j++) {
                        Node StateContent = listaStateContent.item(j);
                        String nameStates = StateContent.getNodeName();
                        if (nameStates.equals("label")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                        if (nameStates.equals("contextName")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                        if (nameStates.equals("selectedImage")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                        if (nameStates.equals("notSelectedImage")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                    }
                    if (numS > 0) {
                        resultado.put(nameState + i, propiedades);
                    }
                }
            }
        } catch (XPathExpressionException e1) {
            e1.printStackTrace();
        } catch (ParserConfigurationException e2) {
            e2.printStackTrace();
        } catch (SAXException e3) {
            e3.printStackTrace();
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        return resultado;
    }

    /**
     * Lectura del fichero xml que figura en la propiedad configurationFile del elemento com.uvigo.mhp.activeImage.ActiveImage
     * @param xmlfilename: nombre del fichero xml
     * @return lista con las propiedades que figuran en el fichero xml
     **/
    public HashMap readValuesComponentsImageAct(String xmlfilename) {

        HashMap resultado = new HashMap();

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaValuesComponents = (NodeList) xpath.evaluate("//activeImageConfiguration/*", doc, XPathConstants.NODESET);
            int num = listaValuesComponents.getLength();
            int numImage = 0;
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node ValuesComponents = listaValuesComponents.item(i);
                String nameState = ValuesComponents.getNodeName();
                if (nameState.equals("activeZone")) {
                    NodeList listaStateContent = ValuesComponents.getChildNodes();
                    HashMap propiedades = new HashMap();
                    int numS = listaStateContent.getLength();
                    if (numS == 0) {
                        return null;
                    }
                    for (int j = 0; j < numS; j++) {
                        Node StateContent = listaStateContent.item(j);
                        String nameStates = StateContent.getNodeName();
                        if (nameStates.equals("contextName")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                        if (nameStates.equals("locator")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                        if (nameStates.equals("comment")) {
                            propiedades.put(nameStates, StateContent.getTextContent());
                        }
                    }
                    if (numS > 0) {
                        resultado.put(nameState + numImage, propiedades);
                    }
                    numImage++;
                }
            }
        } catch (XPathExpressionException e1) {
            e1.printStackTrace();
        } catch (ParserConfigurationException e2) {
            e2.printStackTrace();
        } catch (SAXException e3) {
            e3.printStackTrace();
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        return resultado;
    }

    /**
     * Lectura del fichero xml que figura en la propiedad configurationFile del elemento com.uvigo.mhp.activeImage.ActiveImage
     * @param xmlfilename: nombre del fichero xml
     * @return valor de la propiedad backgroundImage
     **/
    public String readBackgroundImageAct(String xmlfilename) {

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaValuesComponents = (NodeList) xpath.evaluate("//activeImageConfiguration/*", doc, XPathConstants.NODESET);
            int num = listaValuesComponents.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node ValuesComponents = listaValuesComponents.item(i);
                String nameState = ValuesComponents.getNodeName();
                if (nameState.equals("backgroundImage")) {
                    return ValuesComponents.getTextContent();
                }
            }
        } catch (XPathExpressionException e1) {
            e1.printStackTrace();
        } catch (ParserConfigurationException e2) {
            e2.printStackTrace();
        } catch (SAXException e3) {
            e3.printStackTrace();
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        return null;
    }

    /**
     * Lectura del fichero xml que figura en la propiedad contentFile del elemento com.uvigo.mhp.ui.HAnimated
     * @param xmlfilename: nombre del fichero xml
     * @return lista con los valores almacenados en imageLocator
     **/
    public Vector readValuesImageAnimated(String xmlfilename) {

        Vector resultado = new Vector();

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaValuesComponents = (NodeList) xpath.evaluate("//animation/*", doc, XPathConstants.NODESET);
            int num = listaValuesComponents.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node ValuesComponents = listaValuesComponents.item(i);
                String nameState = ValuesComponents.getNodeName();
                if (nameState.equals("imageLocator")) {
                    resultado.add(ValuesComponents.getTextContent());
                }
            }
        } catch (XPathExpressionException e1) {
            e1.printStackTrace();
        } catch (ParserConfigurationException e2) {
            e2.printStackTrace();
        } catch (SAXException e3) {
            e3.printStackTrace();
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        return resultado;
    }

    /**
     * Lectura del fichero xml que figura en la propiedad configurationFile del elemento com.uvigo.mhp.mediaPlayer.MediaPlayer
     * @param xmlfilename: nombre del fichero xml
     * @param namePlayer: nombre del reproductor
     * @return lista con los sellos temporales (timestamp) y subtitulos asociados (comment)
     **/
    public HashMap getTimestamp(String xmlfilename, String namePlayer) {

        HashMap resultado = new HashMap();
        int numberTime = 0;
        //System.out.println("Fichero de TimeStamps: " + xmlfilename);

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            //System.out.println("Docuemnto DOM: " + doc.getDocumentElement());
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaComponentsPlayer = (NodeList) xpath.evaluate("//mediaList/*", doc, XPathConstants.NODESET);
            int num = listaComponentsPlayer.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node ComponentsPlayer = listaComponentsPlayer.item(i);
                String nameComponent = ComponentsPlayer.getNodeName();
                if (nameComponent.endsWith("resource")) {
                    NodeList listaStateContent = (NodeList) xpath.evaluate("//mediaList/" + nameComponent + "/*", doc, XPathConstants.NODESET);
                    int numS = listaStateContent.getLength();
                    if (numS == 0) {
                        return null;
                    }
                    for (int j = 0; j < numS; j++) {
                        Node componente = listaStateContent.item(j);
                        String nameStates = componente.getNodeName();
                        if (nameStates.equals("locator")) {
                            if (!componente.getTextContent().equals(namePlayer)) {
                                break;
                            }
                        }
                        if (nameStates.equals("timestamp")) {
                            Vector time = new Vector();
                            NodeList listaStateContents = componente.getChildNodes();
                            int numk = listaStateContents.getLength();
                            if (numk == 0) {
                                return null;
                            }
                            for (int k = 0; k < numk; k++) {
                                Node timestamp = listaStateContents.item(k);
                                //SSS 26102009 para el control de secuencia de imagenes
                                if (timestamp.getNodeName().equals("contextName")) {
                                    time.add(timestamp.getTextContent());
                                }
                                if (timestamp.getNodeName().equals("timestamp")) {
                                    numberTime++;
                                    time.add(timestamp.getTextContent());
                                }
                                if (timestamp.getNodeName().equals("comment")) {
                                    //System.out.println(timestamp.getTextContent());
                                    time.add(timestamp.getTextContent());
                                }
                            }
                            String np = namePlayer + numberTime;
                            resultado.put(np, time);
                        }
                    }
                }
            }
        } catch (XPathExpressionException e1) {
            e1.printStackTrace();
        } catch (ParserConfigurationException e2) {
            e2.printStackTrace();
        } catch (SAXException e3) {
            e3.printStackTrace();
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        return resultado;
    }

    /**
     * Lectura del fichero xml que figura en la propiedad configurationFile del elemento com.uvigo.mhp.mediaPlayer.MediaPlayer
     * @param xmlfilename: nombre del fichero xml
     * @return nombre del reproductor (locator) 
     **/
    public String getLocatorPlayer(String xmlfilename) {

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaComponentsPlayer = (NodeList) xpath.evaluate("//mediaList/*", doc, XPathConstants.NODESET);
            int num = listaComponentsPlayer.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node componente = listaComponentsPlayer.item(i);
                String nameState = componente.getNodeName();
                if (nameState.endsWith("resource")) {
                    NodeList listaStateContent = (NodeList) xpath.evaluate("//mediaList/" + nameState + "/*", doc, XPathConstants.NODESET);
                    int numS = listaStateContent.getLength();
                    if (numS == 0) {
                        return null;
                    }
                    for (int j = 0; j < numS; j++) {
                        Node cmp = listaStateContent.item(j);
                        String namecmp = cmp.getNodeName();
                        if (namecmp.equals("locator")) {
                            return cmp.getTextContent();
                        }
                    }
                }
            }
        } catch (XPathExpressionException e1) {
            e1.printStackTrace();
        } catch (ParserConfigurationException e2) {
            e2.printStackTrace();
        } catch (SAXException e3) {
            e3.printStackTrace();
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        return "";
    }

    /**
     * Lectura del fichero xml que figura en la propiedad configurationFile del elemento com.uvigo.mhp.textPanel.TextPanel
     * @param xmlfilename: nombre del fichero xml
     * @return lista con los valores de la propiedad locator
     **/
    public HashMap readValuesTextPanel(String xmlfilename) {

        HashMap resultado = new HashMap();

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlfilename);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList listaComponentsPlayer = (NodeList) xpath.evaluate("//documentList/*", doc, XPathConstants.NODESET);
            int num = listaComponentsPlayer.getLength();
            if (num == 0) {
                return null;
            }
            for (int i = 0; i < num; i++) {
                Node componente = listaComponentsPlayer.item(i);
                String namecmp = componente.getNodeName();
                if (namecmp.endsWith("resource")) {
                    NodeList listaStateContent = (NodeList) xpath.evaluate("//documentList/" + namecmp + "/*", doc, XPathConstants.NODESET);
                    int numS = listaStateContent.getLength();
                    if (numS == 0) {
                        return null;
                    }
                    for (int j = 0; j < numS; j++) {
                        Node cmp = listaStateContent.item(j);
                        String nameStates = cmp.getNodeName();
                        if (nameStates.equals("locator")) {
                            resultado.put(nameStates, cmp.getTextContent());
                        }
                    }
                }
            }
        } catch (XPathExpressionException e1) {
            e1.printStackTrace();
        } catch (ParserConfigurationException e2) {
            e2.printStackTrace();
        } catch (SAXException e3) {
            e3.printStackTrace();
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        return resultado;
    }

    /*public static void main(String[] args) {
        String cadena = (String)null;
        Vector vec = new Vector();

        vec.get(0);

        if (cadena.equals(null)) {
            System.out.println("es null");
        } else if(cadena.equals("")) {
            System.out.println("está vacía");
        } else System.out.println(cadena);
    }*/
}
