package com.uvigo.mhp.ui;

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

public class HScrollBar extends HRangeValue implements Serializable {
    private int min, max;
    private HAdjustmentListener adjustmentListener = null;
    private boolean dragging;
    protected boolean isSettingValue;
    
    private String contentFile;
    private JAXBContext jc;
    private MediaTracker trk;
    
    public HScrollBar() {
        super(HOrientable.ORIENT_LEFT_TO_RIGHT, 0, 100, 10, 10, 10, 100, 20);
        
        min=0;
        max=100;
        dragging=false;
        isSettingValue=false;
        enableEvents(AWTEvent.MOUSE_EVENT_MASK+AWTEvent.MOUSE_MOTION_EVENT_MASK);
        
        setForeground(Color.blue);
        setBackground(Color.lightGray);
        try {
            contentFile="";
            trk=new MediaTracker(this);
            jc=JAXBContext.newInstance("com.uvigo.mhp.xml.ui");
            setLook(new HRangeLook1());
        } catch (Exception ex) {
        }
    }
    
    public String getContentFile() {
        return contentFile;
    }
    
    public void setContentFile(String s) {
        String old=contentFile;
        // if (!(s.equals(old)))
        //{
        try {
            if ((s==null) || (s=="")) return;
            
               //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 configuracion no se encuentra o no existe
            ex.printStackTrace();
        }
        //}
    }
    
    public void setLook(HLook hlook) throws HInvalidLookException {
        HLook old=getLook();
        if (hlook!=old) {
            super.setLook(hlook);
            repaint();
            firePropertyChange("look", old, hlook);
        }
    }
    
    public void setOrientation(int orientation) {
        int old=getOrientation();
        if (orientation!=old) {
            super.setOrientation(orientation);
            firePropertyChange("orientation", new Integer(old), new Integer(orientation));
        }
    }
    
    // Para evitar ciclos de llamadas con los HScrollPane que controle
    public boolean isSettingValue() {
        return isSettingValue;
    }
    
    public void setValue(int val) {
        int min=getMinValue();
        int max=getMaxValue();
        int old=getValue();
        if ((val<min) || (val>max))
            return;
        
        if (val!=old) {
            isSettingValue=true;
            super.setValue(val);
            fireEvent(HAdjustmentEvent.ADJUST_END_CHANGE);
            isSettingValue=false;
            repaint();
            firePropertyChange("value", new Integer(old), new Integer(val));
        }
    }
    
    public void setMinValue(int min) {
        int old=getMinValue();
        int max=getMaxValue();
        int cur=getValue();
        if (min>=max) return;
        if (min>cur)
            setValue(min);
        setRange(min, max);
        firePropertyChange("minValue", new Integer(old), new Integer(min));
    }
    
    public void setMaxValue(int max) {
        int old=getMaxValue();
        int min=getMinValue();
        int cur=getValue();
        if (max<=min) return;
        if (max<cur)
            setValue(max);
        setRange(min, max);
        firePropertyChange("maxValue", new Integer(old), new Integer(max));
    }
    
    public void processHAdjustmentEvent(HAdjustmentEvent evt) {
        // se deja vacio para no tener el comportamiento de la superclase
    }
    
    public synchronized void addAdjustmentListener(HAdjustmentListener l) {
        adjustmentListener = HEventMulticaster.add(adjustmentListener, l);
    }
    
    public synchronized void removeAdjustmentListener(HAdjustmentListener l) {
        adjustmentListener = HEventMulticaster.remove(adjustmentListener, l);
    }
    
    protected void processMouseEvent(MouseEvent e) {
        int width=(int) getSize().getWidth();
        int height=(int) getSize().getHeight();
        int x=e.getX();
        int y=e.getY();
        
        HRangeLook look=(HRangeLook) getLook();
        int zone=look.hitTest(this,new Point(x,y));
        switch (e.getID()) {
            case MouseEvent.MOUSE_CLICKED:
            {
                if (!((x>=0) & (x<width) & (y>=0) & (y<height)))
                    break;
                switch(zone) {
                    case HAdjustableLook.ADJUST_PAGE_LESS:
                    case HAdjustableLook.ADJUST_PAGE_MORE:
                        HChangeData changes[]=new HChangeData[1];
                        changes[0]=new HChangeData(1,new Point(x,y));
                        look.widgetChanged(this,changes);
                        fireEvent(HAdjustmentEvent.ADJUST_END_CHANGE);
                        break;
                }
                break;
            }
            case MouseEvent.MOUSE_PRESSED:
            {
                if (!((x>=0) & (x<width) & (y>=0) & (y<height))) break;
                
                if (zone==HAdjustableLook.ADJUST_THUMB) {
                    dragging=true;
                    fireEvent(HAdjustmentEvent.ADJUST_START_CHANGE);
                }
                break;
            }
            case MouseEvent.MOUSE_RELEASED:
            {
                if (dragging)
                    fireEvent(HAdjustmentEvent.ADJUST_END_CHANGE);
                dragging=false;
                break;
            }
        }
    }
    
    protected void processMouseMotionEvent(MouseEvent e) {
        int width=(int) getSize().getWidth();
        int height=(int) getSize().getHeight();
        int x=e.getX();
        int y=e.getY();
        
        if (e.getID()!=MouseEvent.MOUSE_DRAGGED) {
            dragging=false;
            return;
        }
        
        if (!dragging)
            return;
        
        if (!((x>=0) & (x<width) & (y>=0) & (y<height))) return;
        
        HRangeLook look=(HRangeLook) getLook();
        
        HChangeData changes[]=new HChangeData[1];
        changes[0]=new HChangeData(1,new Point(x,y));
        look.widgetChanged(this,changes);
        fireEvent(HAdjustmentEvent.ADJUST_END_CHANGE);
    }
    
    private void fireEvent(int id) {
        if (adjustmentListener != null)
            adjustmentListener.valueChanged(new HAdjustmentEvent(this,id));
    }
}
