package tmaestroplayer;

import edutainmentclient.Main;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.media.ControllerEvent;
import javax.media.EndOfMediaEvent;
import javax.media.Player;
import javax.media.StartEvent;
import javax.media.StopEvent;
import javax.media.Time;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;

//import tm.applet.AppletTemplateComponentsXML.TimerListener;
import javax.swing.SwingConstants;
import org.jdom.Namespace;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import tmaestroplayer.template.TemplateComponentsJavaXML;

public class VentanaSeleccionCurso extends JInternalFrame /*implements ControllerListener*/ {

    // Unidad del curso
    //SSS 26102009 debería estar publico
    public Unit unidadPrincipal;
    // Ruta del imsmanifest.xml y de los recursos asociados
    private String path;
    // Se india el Applet para la representaci�n del contenido 
    //SSS 26102009 aqui lo tengo publco
    //private CVApplet applet;
    //Ahora es una referencia a un JFrame
    public MainWindow_portada frame;
    public String nombreCurso;
    // idCliente necesario para la comunicaci�n con el servidor
    private String nameCliente = null;
    //nombre de la opcion a reproducir en los SCOs
    private String option;
    // Vector que contiene los elementos del estilo
    // M�sica de fondo del men�
    public Player player; //era private
    // Variable que indica instante de reproducci�n
    public double timer = 0;//
    // Variables para la representaci�n de los componentes
    private URL dirURLup = null;
    private URL dirURLdown = null;
    String name = null;
    java.awt.Color colorn = Color.blue;
    java.awt.Color colorf = Color.red;
    // Componentes graficos del menu de un curso
   /*
    private javax.swing.JLabel jLabel0;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    
     */
    private javax.swing.JLabel[] jLabel;
    private javax.swing.JLabel jLabelBACK;
    private javax.swing.JLabel jLabelBACKGROUNDIMAGE;
    private javax.swing.JLabel jLabelDOWN;
    private javax.swing.JLabel jLabelEXIT;
    private javax.swing.JLabel jLabelRIGHT;
    private javax.swing.JLabel jLabelLEFT;
    private javax.swing.JLabel jLabelRIGHT2;
    private javax.swing.JLabel jLabelLEFT2;
    private javax.swing.JLabel jLabelINFO;
    private javax.swing.JLabel jLabelINFO2;
    private javax.swing.JLabel jLabelUP;
    // Indica cual es el primer elemento de la lista
    //estaba a 8
    int offset = 0;
    // Indica cual es el elemento que tiene el focus
    public int focused = 0;
    public VentanaSeleccionCurso vsupadre; //
    TemplateComponentsJavaXML atcjx;
    final private int LEFT = 0;
    final private int CENTER = 1;
    final private int RIGHT = 2;
    private int currentPosition = 1;
    Vector<String> listaCursos;

    //public VentanaSeleccionUnidad(Unit unidades[], String path, CVApplet applet, String optionName, Vector vstyle, double timePlayer, VentanaSeleccionUnidad vsupadre) {
    public VentanaSeleccionCurso(Vector<String> listaCursos, MainWindow_portada frame, String optionName, VentanaSeleccionCurso vsupadre) {
        System.out.println("VentanaSeleccionCurso");
        this.vsupadre = vsupadre;

        //this.applet = applet;
        this.frame = frame;
        //this.nameCliente = nameclnt;
        this.option = optionName;
        this.listaCursos = listaCursos;
        initComponents(listaCursos.size());
        //   initComponents(1);
    }

    private static void addComponent(Container frame, Component component, int gridx, int gridy,
            int gridwidth, int gridheight, GridBagConstraints c) {

        c.gridx = gridx;
        c.gridy = gridy;
        c.gridwidth = gridwidth;
        c.gridheight = gridheight;

        frame.add(component, c);
    }

    private String leerTitulo(String ruta) {


        SAXBuilder builder = new SAXBuilder(false);
        org.jdom.Document doc = null;

        String namem = "imsmanifest.xml";
        String rutat = ruta + "/" + namem;


        try {
            doc = builder.build(new URL(rutat));
        } catch (JDOMException ex) {
            //Logger.getLogger(VentanaSeleccionCurso.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        } catch (IOException ex) {
            //Logger.getLogger(VentanaSeleccionCurso.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
        //Construyo el arbol en memoria desde el fichero que se lo paso por parametro.
        org.jdom.Element raiz = doc.getRootElement();



        Namespace manifestNS = raiz.getNamespace();
        // metadataNS = raiz.getNamespace("imsmd");
        org.jdom.Element organizations = raiz.getChild("organizations", manifestNS);
        List organizationList = organizations.getChildren("organization", manifestNS);
        List<Unit> units = new LinkedList<Unit>();
        for (Object obj : organizationList) {
            if (obj instanceof org.jdom.Element) {
                org.jdom.Element element = (org.jdom.Element) obj;
                return element.getChild("title", manifestNS).getTextTrim();
            }
        }
        return null;
    }

    /*******************************************************************************
     *        Inicializa los componentes gr�ficos del men� del curso               *
     *******************************************************************************/
    private void initComponents(int numItems) {
        jLabel = new JLabel[numItems];

        frame.getContentPane().setBackground(new Color(162, 190, 255));
        GridBagLayout g = new GridBagLayout();
        frame.setLayout(g);
        frame.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1;
        c.weighty = 1;
        //primera fila


        // Row One - Three Buttons
        c.weighty = 0.16;
        //el primero vacio

        // addComponent(frame, button, 0, 0, 1, 1, c);

        jLabelINFO = new JLabel("Welcome " + Main.userId + "! Please, select a course to start:");
        // jLabelINFO = new JLabel("Welcome Paul! Please, select a course to resume");
        jLabelINFO.setFont(new Font("Dialog", Font.BOLD, 18));
        jLabelINFO.setHorizontalAlignment(SwingConstants.CENTER);
        jLabelINFO.setBackground(new java.awt.Color(255, 255, 255));
        jLabelINFO.setPreferredSize(new java.awt.Dimension(500, 50));
        jLabelINFO.setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(0, 0, 0)));
        jLabelINFO.setOpaque(true);
        c.fill = GridBagConstraints.HORIZONTAL;
        addComponent(frame, jLabelINFO, 1, 0, 6, 1, c);

        c.fill = GridBagConstraints.NONE;

        ImageIcon exitIcon = new ImageIcon();

        // image = (new javax.swing.ImageIcon(Main.class.getResource("/resources/birrete.gif"))).getImage();

        exitIcon.setImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/resources/exit_button.jpg")));
        jLabelEXIT = new JLabel();
        jLabelEXIT.setIcon(exitIcon);
        jLabelEXIT.setHorizontalAlignment(SwingConstants.LEFT);
        addComponent(frame, jLabelEXIT, 7, 0, 1, 1, c);
        jLabelEXIT.addMouseListener(new java.awt.event.MouseListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
            }

            public void mouseEntered(MouseEvent arg0) {
                jLabel[0].setBorder(null);
                jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(255, 0, 0)));
            }

            public void mouseExited(MouseEvent arg0) {
                jLabelEXIT.setBorder(null);
            }

            public void mousePressed(MouseEvent arg0) {
                System.out.println("Se pulsó exit en la vsu");
                Main.edutainmentStopEvent(null, null, null);
                dispose();

                frame.panel.setVisible(false);

                frame.dispose();
                Main.sendRulDelMessage();

                
                System.exit(0);
            }

            public void mouseClicked(MouseEvent arg0) {
            }

            public void mouseReleased(MouseEvent arg0) {
            }
        });

        // Row Two - Two Buttons
        c.weighty = 0.32;

        ImageIcon leftIcon = new ImageIcon();
        leftIcon.setImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/resources/Red_left_arrow.png")));

        jLabelLEFT = new JLabel();
        jLabelLEFT.setIcon(leftIcon);
        if (numItems > 3) {
            addComponent(frame, jLabelLEFT, 0, 1, 1, 3, c);
        }
        jLabelLEFT.addMouseListener(new java.awt.event.MouseListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
            }

            public void mouseEntered(MouseEvent arg0) {
                jLabel[0].setBorder(null);
                jLabelLEFT.setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(255, 0, 0)));
            }

            public void mouseExited(MouseEvent arg0) {
                jLabelLEFT.setBorder(null);
            }

            public void mousePressed(MouseEvent arg0) {
                System.out.println("Se pulsó left");
                //focused = 5;
                focused = 5 + offset;
                //goENTER(listaCursos.get(5));
                nombreCurso = listaCursos.get(5);
            }

            public void mouseClicked(MouseEvent arg0) {
            }

            public void mouseReleased(MouseEvent arg0) {
            }
        });


        ImageIcon rightIcon = new ImageIcon();
        rightIcon.setImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/resources/Red_right_arrow.png")));
        jLabelRIGHT = new JLabel();
        jLabelRIGHT.setIcon(rightIcon);
        if (numItems > 3) {
            addComponent(frame, jLabelRIGHT, 7, 1, 1, 3, c);
        }
        jLabelRIGHT.addMouseListener(new java.awt.event.MouseListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
            }

            public void mouseEntered(MouseEvent arg0) {
                jLabel[0].setBorder(null);
                jLabelRIGHT.setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(255, 0, 0)));
            }

            public void mouseExited(MouseEvent arg0) {
                jLabelRIGHT.setBorder(null);
            }

            public void mousePressed(MouseEvent arg0) {
                System.out.println("pulse right");
                //focused = 5;
                focused = 5 + offset;
                //goENTER(listaCursos.get(5));
                nombreCurso = listaCursos.get(5);
            }

            public void mouseClicked(MouseEvent arg0) {
            }

            public void mouseReleased(MouseEvent arg0) {
            }
        });

        // Row Three - Two Buttons
        c.weighty = 0.16;
       

        frame.setVisible(true);

        pack();
        setVisible(true);

        final java.awt.Color colorNormal = Color.blue;
        final java.awt.Color colorFocused = Color.red;

        for (int i = 0; i < numItems; i++) {
            jLabel[i] = new JLabel();
            jLabel[i].setHorizontalAlignment(JLabel.CENTER);
            jLabel[i].setVerticalAlignment(JLabel.CENTER);
            System.out.println("leer titulo " + leerTitulo(listaCursos.get(i)));
            jLabel[i].setText(leerTitulo(listaCursos.get(i)));
            jLabel[i].setVerticalTextPosition(SwingConstants.BOTTOM);
            jLabel[i].setHorizontalTextPosition(SwingConstants.CENTER);
            jLabel[i].setForeground(colorNormal);
            if (focused == i) {
                //00 204 00= #00cc00 color verde de alrededor
                jLabel[i].setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(0, 204, 0)));
            }

            // jLabel0.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            try {
                System.out.println(listaCursos.get(i));
                jLabel[i].setIcon(new javax.swing.ImageIcon(new URL((String) listaCursos.get(i) + "/icon.jpg")));

            } catch (MalformedURLException ex) {
                Logger.getLogger(VentanaSeleccionCurso.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (i < 3) {
                addComponent(frame, jLabel[i], 1 + i * 2, 1, 2, 3, c);
            }
            //this.add(jLabel0);
            final int a = i;
            jLabel[i].addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, a);
                    jLabel[a].setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(0, 204, 0)));
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel[a].setForeground(colorNormal);
                    // jLabel0.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                    jLabel[a].setBorder(null);
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 0;
                    focused = a + offset;

                    goENTER(listaCursos.get(a));
                    nombreCurso = listaCursos.get(a);
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });

        }
       

        pack();

    }

    /*******************************************************************************
     *          Acciones relacionadas con los eventos del teclado                  *
     *******************************************************************************/
    private void formKeyPressed(java.awt.event.KeyEvent evt) {
        VentanaSeleccionCurso vsuOrig = (VentanaSeleccionCurso) evt.getSource();
        System.out.println("Se recibió una pulsación de tecla en al vsu: " + vsuOrig.unidadPrincipal.getName());
        switch (evt.getKeyCode()) {
            case KeyEvent.VK_UP:
                goUP();
                break;
            case KeyEvent.VK_DOWN:
                goDOWN();
                break;
            case KeyEvent.VK_LEFT:
                goLEFT();
                break;
            case KeyEvent.VK_RIGHT:
                goRIGHT();
                break;
            case KeyEvent.VK_ENTER:
                switch (currentPosition) {
                    case LEFT:

                        break;
                    case CENTER:
                        goENTER();
                        break;
                    case RIGHT:

                        break;
                }
                break;
        }
    }

    public void upEvent() {
        goUP();
    }

    public void downEvent() {
        goDOWN();
    }

    public void leftEvent() {
        goLEFT();
    }

    public void rightEvent() {
        goRIGHT();
    }

    public void enterEvent() {
        switch (currentPosition) {
            case LEFT:

                break;
            case CENTER:
                goENTER();
                break;
            case RIGHT:

                break;
        }
    }

    private void goUP() {
        if (currentPosition == CENTER) {
            setFocused(focused - 1);
        }
    }

    private void goDOWN() {
        if (currentPosition == CENTER) {
            setFocused(focused + 1);
        }
    }

    private void goLEFT() {
        switch (currentPosition) {
            case LEFT:
                break;
            case CENTER:

                setFocused(focused - 1);
                /*
                if (vsupadre != null) {
                jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, java.awt.Color.YELLOW));
                currentPosition = LEFT;
                setUnfocused(focused);
                }

                 */
                break;
            case RIGHT:
                jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(255, 0, 0)));
                currentPosition = CENTER;
                setFocused(focused);
                break;
        }
    }

    private void goRIGHT() {
        System.out.println("goRight "+currentPosition);
        switch (currentPosition) {
            case LEFT:
                jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(0, 204, 0)));
                currentPosition = CENTER;
                setFocused(focused);
                break;
            case CENTER:
                setFocused(focused + 1);
                /*
                jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, java.awt.Color.YELLOW));
                currentPosition = RIGHT;
                setUnfocused(focused);
                 *
                 */
                break;
            case RIGHT:
                break;
        }
    }

    /**************************************************************************************
     * Envio al servidor TM el idSCO seleccionado y reproduce en pantalla la opci�n dada  *
     **************************************************************************************/
    //SSS 26102009 esta public
    private void goENTER(String courseURL) {
        System.out.println("goEnter " + courseURL);
        int offsett = 0;
        if (courseURL.contains("\"")) {
            offsett = 1;
        }

        Main.rutascorm = courseURL.substring(0, courseURL.lastIndexOf("/") + 1);
        Main.nombrecurso = courseURL.substring(courseURL.lastIndexOf("/") + 1, courseURL.length() - offsett) + "/";


        frame.rutaScorm = Main.rutascorm;
        frame.nombreCurso = Main.nombrecurso;
        System.out.println(Main.rutascorm + "    " + Main.nombrecurso);


        //frame.panel.setVisible(false);

        frame.remove(jLabel[0]);
        frame.remove(jLabel[1]);
        frame.remove(jLabel[2]);

        frame.remove(jLabelLEFT);

        frame.remove(jLabelRIGHT);

        frame.remove(jLabelINFO);

        frame.remove(jLabelEXIT);
        /*
        frame.remove(jLabel3);
        frame.remove(jLabel4);
        frame.remove(jLabel5);
        frame.remove(jLabelLEFT2);
        frame.remove(jLabelRIGHT2);
        frame.remove(jLabelINFO2);
         */
        frame.dispose();

        MainWindow mw = new MainWindow(Main.userId, true);
        Main.mw = mw;
        mw.init();


        //frame.add(mw.panel);


        //CourseLoader oCL = new CourseLoader(mw);
        //JDesktopPane panel = (JDesktopPane) oCL.getVisual();




//mw.getContentPane().add(panel);


        // frame.add(panel);
        // frame.repaint();





    }

    private void goENTER() {
        System.out.println("goEnter");
        goENTER(listaCursos.get(focused));
    }

    /*******************************************************************************
     *                       Opciones de reproductor                               *
     *******************************************************************************/
    public void stopPlayerUnidades() {
        //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
        if (frame.bgMusicPlayer != null) {
            frame.bgMusicPlayer.removeControllerListener(frame);
            frame.bgMusicPlayer.stop();
            frame.bgMusicPlayer.setMediaTime(new Time(0));
            frame.bgMusicPlayer.close();
        }
        /*if (player != null) {
        player.stop();
        player.setMediaTime(new Time(0));
        }*/
    }

    public void startPlayerUnidades() {
        if (frame.bgMusicPlayer != null) {
            System.out.println("musicstart");
            frame.bgMusicPlayer.addControllerListener(frame);
            frame.bgMusicPlayer.start();
        }
    }

    public void startPlayerUnidades(Player p, boolean calledFromSon) {
        if (p != null) {
            //Si existe una ventana padre paramos su reproductor y copiamos el valor del tiempo de reproducción
            if (vsupadre != null && !calledFromSon) {
                this.timer = vsupadre.player.getMediaTime().getSeconds();
                vsupadre.stopPlayerUnidades();
            }
            p.setMediaTime(new Time(timer));
            System.out.println("Valor de this.timer: " + this.timer + "\nValor de p.getMediaTime: " + p.getMediaTime().getSeconds());
            p.start();
        }
    }

    private void pausePlayerUnidades() {
        //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
        if (frame.bgMusicPlayer != null) {
            frame.bgMusicPlayer.removeControllerListener(frame);
            frame.bgMusicPlayer.stop();
        }
        /*if (player != null) {
        player.stop();
        }*/
    }

    /*******************************************************************************
     *                 Establece los elementos visibles en pantalla                 *
     *******************************************************************************/
    private void setUnitsCells(int elemento) {

        if (elemento >= offset && elemento < offset + 8) {
            return;
        }

        Unit[] subunidades = unidadPrincipal.getSubUnits();
        if (elemento < offset) {
            offset = elemento;
        } else if (elemento >= offset + 8) {
            offset = elemento - 7;
        }

        int ini = offset;
        int finNOR = offset + 8;
        int finR = subunidades.length;
        int fin = Math.min(finR, finNOR);

        for (int i = ini; i < fin; i++) {
            getLabel(i).setText(subunidades[i].getName());
            getLabel(i).setForeground(colorn);
        }

        for (int i = finR; i < finNOR; i++) {
            getLabel(i).setText(null);
            getLabel(i).setIcon(null);
        }

        if (offset > 0) {
            jLabelUP.setIcon(new javax.swing.ImageIcon(dirURLup));
        } else {
            jLabelUP.setIcon(null);
        }

        if (offset + 7 < subunidades.length - 1) {
            jLabelDOWN.setIcon(new javax.swing.ImageIcon(dirURLdown));
        } else {
            jLabelDOWN.setIcon(null);
        }
    }

    /*******************************************************************************
     *            Establece el "foco" en un determinado objeto                     *
     *******************************************************************************/
    private void setFocused(int f) {
        if (f < 0) {
            f = 2;
        }
        if (f > 2) {
            f = 0;
        }
        //System.out.println("setFocused " + f);

        getLabel(focused).setForeground(colorn);
        getLabel(focused).setBorder(null);


        // getLabel(focused).setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
        getLabel(f).setForeground(colorf);
        getLabel(f).setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(0, 204, 0)));

        // getLabel(f).setFont(new Font(namef, Integer.parseInt(fontstylef), Integer.parseInt(sizef)));



        focused = f;
        //System.out.println("setFocused: foco " + focused);
    }

    /*******************************************************************************
     *            Elimina el foco de una de las opciones, se utiliza               *
     *            nos desplazamos lateralmente con el mando o teclado              *
     * @param f                                                                    *
     *******************************************************************************/
    private void setUnfocused(int f) {
        getLabel(focused).setForeground(colorn);
        // getLabel(focused).setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
        //System.out.println("setUnfocused: foco quitado a " + focused);
    }

    /*******************************************************************************
     *          Establece el "foco" en el objeto seleccionado con el rat�n         *
     *******************************************************************************/
    //SSS 26102009 yo lo tengo publico para el next
    private void setFocusedMouse(int fanterior, int factual) {
        System.out.println("fanterior " + fanterior + " factual " + factual);
        //Al seleccionar una de las etiquetas con el ratón tenemos que comprobar
        //si nos habíamos movido a los botones de atrás o exit con el mando/teclado
        //de ser así, tenemos que desactivarles el estado de "focused"
        //si estamos en el botón BACK con el mando
        if (currentPosition == LEFT) {
            jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(0, 204, 0)));
        } else if (currentPosition == RIGHT) {//Si estamos en el botón EXIT con el mando
            jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(255, 0, 0)));
        }//Si estabamos en las "etiquetas" no hacemos nada
        //En cualquier caso cambiamos la posición al "centro"
        currentPosition = CENTER;


        //SSS 26102009 yo esto no lo tengo, manejamos el offset distinto
        factual = factual + offset;


        setUnitsCells(factual);

        getLabel(fanterior).setForeground(colorn);
        // getLabel(fanterior).setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
        getLabel(factual).setForeground(colorf);
        // getLabel(factual).setFont(new Font(namef, Integer.parseInt(fontstylef), Integer.parseInt(sizef)));



        focused = factual;
        //System.out.println("setFocusedMouse: foco " + focused);
    }

    /*******************************************************************************
     *         Obtiene la etiqueta correspondiente a un determinado indice         *
     *******************************************************************************/
    private JLabel getLabel(int i) {
        //System.out.println(i);
        //System.out.println((i - offset)%3);
        //estaba a 8
        return jLabel[(i - offset) % 3];
        /*
        switch ((i - offset) % 3) { // i-offset debe ser SIEMPRE >= 0
        case 0:
        // System.out.println("jlabel0");
        return jLabel[0];
        case 1:
        //System.out.println("jlabel1");
        return jLabel[1];
        case 2:
        // System.out.println("jlabel2");
        return jLabel2;
        case 3:
        // System.out.println("jlabel3");
        return jLabel3;
        case 4:
        // System.out.println("jlabel4");
        return jLabel4;
        case 5:
        // System.out.println("jlabel5");
        return jLabel5;
        case 6:
        //System.out.println("jlabel6");
        return jLabel6;
        case 7:
        // System.out.println("jlabel7");
        return jLabel7;
        default:
        //  System.out.println("default");
        return null;

        }

         */
    }

    public void controllerUpdate(ControllerEvent oCE) {
        if (oCE instanceof EndOfMediaEvent) {
            // System.out.println("reiniciando el reproductor de música de fondo");
            player.setMediaTime(new Time(0));
            player.start();
            /*JInternalFrame jif = applet.panel.getSelectedFrame();
            if (jif instanceof LoginFrame) {
            System.out.println("Está seleccionada la loginFrame");
            } else if (jif instanceof VentanaSeleccionUnidad) {
            String vsuName = ((VentanaSeleccionUnidad) jif).unidadPrincipal.getName();
            System.out.println("Está seleccionada la vsu: " + vsuName);
            } else {
            System.out.println("No se de que tipo es la JInternalFrame");
            }*/
        } else if (oCE instanceof StartEvent) {
            //System.out.println("**player started");
        } else if (oCE instanceof StopEvent) {
            System.out.println("**player stopped!!");
        }
    }
}

