package com.uvigo.mhp.mediaPlayer;

import java.awt.*;
import java.awt.event.*;
import javax.media.*;
import javax.swing.*;

public class MediaScrollBar extends javax.swing.JScrollBar implements ControllerListener, AdjustmentListener
{
    private Player player;
    private long duration;
    private boolean dragging;
    private int pressX, pressY, pressValue;
    private MediaScrollBarThread thread;
    
    public MediaScrollBar(Player player)
    {
        super(Adjustable.HORIZONTAL, 0, 1, 0, 100);
        this.player=player;
        duration=player.getDuration().getNanoseconds();
        thread=new MediaScrollBarThread(this,player);
        thread.start();
        player.addControllerListener(this);
        addAdjustmentListener(this);
    }
    
    public void controllerUpdate(ControllerEvent event)
    {
        if (event instanceof MediaTimeSetEvent)
        {
            int pos=(int)((double) player.getMediaTime().getNanoseconds()/(double) player.getDuration().getNanoseconds()*100);
            setValue(pos);
            return;
        }
        
        if (event instanceof StartEvent)
        {
            thread.on();
        }
        if ((event instanceof StopEvent))
        {
            thread.off();
        }
    }
    
    public void adjustmentValueChanged(AdjustmentEvent e)
    {
        boolean isPlaying=(player.getState()==Player.Started) ? true : false;
        int cur=getValue();
        long pos=(long) (((double)(cur))*duration/((double)(100)));
        
        if (!isPlaying)
        {
            player.setMediaTime(new Time(pos));
            return;
        }
    }
}