package com.uvigo.mhp.ui;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import org.havi.ui.*;
import org.havi.ui.event.*;
import javax.xml.bind.*;
import com.uvigo.mhp.looks.*;
import com.uvigo.mhp.xml.ui.*;
import com.uvigo.tMaestro.SCOCreator.tool.MainFrame;

// Debe lanzar 2 tipos de eventos: al activar y al desactivar!!!
public class HSwitch extends HToggleButton implements Serializable, FocusListener {
 public static final int TIME_ALWAYS = 0;
    public static final int TIME_OK = 1;
    public static final int TIME_WRONG = 2;
    public static final int TIME_DELAYED = 4;
    public static final int TIME_LIMITED = 6;
    
    private ActionListener actionListener = null;
    private boolean fireEventsWhileActioned;
    protected int millisBetweenEvents;
    private HActionedThread thread;
    private String contentFile;
    private int delayedTimeMode;
    private int delayedTime;
    private JAXBContext jc;
    private MediaTracker trk;

    public HSwitch() {
        enableEvents(AWTEvent.MOUSE_EVENT_MASK);
        addFocusListener(this);
        fireEventsWhileActioned = false;
        delayedTimeMode=TIME_ALWAYS;
        delayedTime=0;
        millisBetweenEvents = 100;
        thread = null;
        trk = new MediaTracker(this);

        try {
            jc = JAXBContext.newInstance("com.uvigo.mhp.xml.ui");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        try {
            Image img1, img2;
            img1 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("na.gif"));
            img2 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("ap.gif"));

            trk.addImage(img1, 0);
            trk.addImage(img2, 1);
            trk.waitForAll();

            setGraphicContent(img1, HState.NORMAL_STATE);
            setGraphicContent(img2, HState.ACTIONED_STATE);
            setGraphicContent(img2, HState.ACTIONED_FOCUSED_STATE);
            setGraphicContent(img1, HState.FOCUSED_STATE);

            setLook(new HGraphicLook1());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 public int getDelayedTimeMode() {
        return delayedTimeMode;
    }

    public void setDelayedTimeMode(int i) {

        int old = delayedTimeMode;
        if (i != old) {
            delayedTimeMode = i;
            repaint();
            firePropertyChange("delayedTimeMode", new Integer(old), new Integer(i));

        }
    }
    
    
    public int getDelayedTime() {
        return delayedTime;
    }

    public void setDelayedTime(int m) {
        int old = delayedTime;
        if (m != old) {
            delayedTime = m;
            firePropertyChange("delayedTime", new Integer(old), new Integer(m));
        }
    }
    public String getContentFile() {
        return contentFile;
    }

    public void setContentFile(String s) {
        String old = contentFile;
        // if (!(s.equals(old))) { //Necesario eliminarlo, ya que puede cambiar el contenido del fichero y no su ruta

        try {
            //M: imagenes de inicializaci�n
            if ((s == null) || (s == "")) {//-M-
                Image img1, img2;
                img1 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("na.gif"));
                img2 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("ap.gif"));

                trk.addImage(img1, 0);
                trk.addImage(img2, 1);
                trk.waitForAll();

                setGraphicContent(img1, HState.NORMAL_STATE);
                setGraphicContent(img2, HState.ACTIONED_STATE);
                setGraphicContent(img2, HState.ACTIONED_FOCUSED_STATE);
                setGraphicContent(img1, HState.FOCUSED_STATE);

            }

              //M: Direccionamiento relativo a "user.dir"
            String sBase = new String(MainFrame.oMainFrame.sDir + "/");
            URL url = new URL("file:" + sBase + s);

            //Parte de s que corresponde a ruta (que no es fichero)
            String[] split = s.split("/");
            String sRuta = new String();
            int z = 0;
            for (z = 0; z < split.length - 1; z++) {
                sRuta = sRuta.concat(split[z] + "/");
            }

            URLConnection con = url.openConnection();

            Unmarshaller u = jc.createUnmarshaller();
            u.setValidating(true);
            ContentList clist = (ContentList) u.unmarshal(con.getInputStream());

            ContentType ctemp[] = new ContentType[8];
            ctemp[0] = clist.getNormalStateContent();
            ctemp[1] = clist.getFocusedStateContent();
            ctemp[2] = clist.getActionedStateContent();
            ctemp[3] = clist.getActionedFocusedStateContent();
            ctemp[4] = clist.getDisabledStateContent();
            ctemp[5] = clist.getDisabledFocusedStateContent();
            ctemp[6] = clist.getDisabledActionedStateContent();
            ctemp[7] = clist.getDisabledActionedFocusedStateContent();

            Image itemp[] = new Image[8];
            for (int i = 0; i < 8; i++) {
                if (ctemp[i].getGraphicContent() == null) continue;
                if (ctemp[i].getGraphicContent().equals("")) continue;

                URL temp = new URL("file:" + sBase + sRuta + ctemp[i].getGraphicContent());
                itemp[i] = Toolkit.getDefaultToolkit().getImage(temp);
                trk.addImage(itemp[i], i);
            }

            trk.waitForAll();

            // Si todo se ha cargado correctamente, se inicializa el contenido
            for (int i = HState.NORMAL_STATE; i < HState.DISABLED_ACTIONED_FOCUSED_STATE; i++) {
                setTextContent(ctemp[i - HState.NORMAL_STATE].getTextContent(), i);
                setGraphicContent(itemp[i - HState.NORMAL_STATE], i);
            }

            contentFile = s;
            firePropertyChange("contentFile", old, s);
            repaint();
        } catch (Exception ex) {
            // El fichero de configuraci�n no se encuentra o no existe
            ex.printStackTrace();
        }
    //}
    }

    public boolean getFireEventsWhileActioned() {
        return fireEventsWhileActioned;
    }

    public void setFireEventsWhileActioned(boolean b) {
        boolean old = fireEventsWhileActioned;
        if (b != old) {
            fireEventsWhileActioned = b;
            firePropertyChange("fireEventsWhileActioned", new Boolean(old), new Boolean(b));
        }
    }

    public int getMillisBetweenEvents() {
        return millisBetweenEvents;
    }

    public void setMillisBetweenEvents(int m) {
        int old = millisBetweenEvents;
        if (m != old) {
            millisBetweenEvents = m;
            firePropertyChange("millisBetweenEvents", new Integer(old), new Integer(m));
        }
    }

    public HSwitchGroup getSwitchGroup() {
        return (HSwitchGroup) getToggleGroup();
    }

    public void setSwitchGroup(HSwitchGroup g) {
        HSwitchGroup old = (HSwitchGroup) getToggleGroup();
        if (g != old) {
            setToggleGroup(g);
            firePropertyChange("switchGroup", old, g);
        }
    }

    public void processHActionEvent(HActionEvent evt) {
    // se deja vac�o para no tener el comportamiento de la superclase
    }

    public synchronized void addActionListener(ActionListener l) {
        actionListener = AWTEventMulticaster.add(actionListener, l);
    }

    public synchronized void removeActionListener(ActionListener l) {
        actionListener = AWTEventMulticaster.remove(actionListener, l);
    }

    protected void fireEvent() {
        if (actionListener != null)
            actionListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_FIRST, getActionCommand()));
    }

    protected void processMouseEvent(MouseEvent e) {
        if (!isEnabled())
            return;

        int width = (int) getSize().getWidth();
        int height = (int) getSize().getHeight();
        int x = e.getX();
        int y = e.getY();

        switch (e.getID()) {
            case MouseEvent.MOUSE_ENTERED:
                if (!(this.hasFocus()))
                    requestFocus();
                break;
            case MouseEvent.MOUSE_PRESSED:
                if (!((x >= 0) & (x <= width) & (y >= 0) & (y <= height))) return;
                if ((getInteractionState() & HState.ACTIONED_STATE_BIT) > 0) {
                    // estaba activado, hay que desactivarlo
                    setInteractionState(HState.FOCUSED_STATE);
                    break;
                } else {
                    // estaba desactivado, hay que activarlo
                    setInteractionState(HState.ACTIONED_FOCUSED_STATE);
                    break;
                }
            default:
                break;
        }
    }

    public void focusGained(java.awt.event.FocusEvent focusEvent) {
        int state = getInteractionState();
        state = state | HState.FOCUSED_STATE_BIT;
        setInteractionState(state);
    }

    public void focusLost(java.awt.event.FocusEvent focusEvent) {
        int state = getInteractionState();
        state = state & (~(HState.FOCUSED_STATE_BIT));
        setInteractionState(state);
    }

    public void setInteractionState(int state) {
        int old = getInteractionState();
        if (state == old) return;

        super.setInteractionState(state);

        if ((state & HState.ACTIONED_STATE_BIT) > 0) {
            // hay que accionar el switch, pero s�lo si no lo estaba ya
            if ((old & HState.ACTIONED_STATE_BIT) > 0) return;
            if (fireEventsWhileActioned) {
                if (thread == null) {
                    thread = new HActionedThread(this, millisBetweenEvents);
                    thread.start();
                }
            } else
                fireEvent();
        } else if (thread != null) {
            thread.off();
            thread = null;
        }
    }
}
