/**
 * StatusIndicator.java
 *
 * @author Created by Omnicore CodeGuide
 */

package edu.sc.seis.gee.task;

import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.Timer;
import edu.sc.seis.fissuresUtil.cache.JobTracker;
import edu.sc.seis.fissuresUtil.cache.TrackerListener;
import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler;
import edu.sc.seis.gee.CommonAccess;
import edu.sc.seis.gee.configurator.ConfigurationException;

public class StatusIndicator extends JButton implements TrackerListener, ActionListener{
    public StatusIndicator(){
        this(null);
    }
    public StatusIndicator(String label){
        super(label);
        if(apples == null){
            generateApples();
        }
        if(updateTimer == null){
            updateTimer = new Timer(wait, this);
            updateTimer.setCoalesce(true);
            updateTimer.start();
        }else{
            updateTimer.addActionListener(this);
        }
        setIcon(apples[0]);
        setMargin(new Insets(0,0,0,0));
        JobTracker.getTracker().add(this);
        addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        try {
                            CommonAccess.getCommonAccess().getTaskAction("JobDisplay").checkDisplayLocation(false);
                        } catch (ConfigurationException ex) {
                            GlobalExceptionHandler.handle("Unable to show Job display", ex);
                        }
                    }
                });
    }

    public synchronized void trackerUpdated(JobTracker tracker) {
        activeJobs = tracker.getActiveJobs().size();
    }

    public void actionPerformed(ActionEvent e){
        if(pos != 0 || activeJobs > 0){
            if(up){
                pos++;
                setIcon(apples[pos]);
                if(pos == 4){
                    up = false;
                }
            }else{
                pos--;
                setIcon(apples[pos]);
                if(pos == 0){
                    up = true;
                }
            }
        }
    }

    private boolean up = true;

    private int activeJobs = 0;

    private int pos = 0;

    public void destroy(){
        JobTracker.getTracker().remove(this);
        updateTimer.removeActionListener(this);
    }

    private void generateApples(){
        ImageIcon[] genApples = { get(1), get(2), get(3), get(4), get(5) };
        apples = genApples;
    }

    private static ImageIcon[] apples = null;

    private ImageIcon get(int appleNum){
        return new ImageIcon(getClass().getClassLoader().getResource("edu/sc/seis/gee/data/images/apples/apple" + appleNum + ".png"));
    }

    private static Timer updateTimer = null;

    private static final int wait = 100;
}


