package org.jfox.ejb.timer;

import java.io.Serializable;
import java.util.Date;
import javax.ejb.EJBException;
import javax.ejb.NoSuchObjectLocalException;
import javax.ejb.Timer;
import javax.ejb.TimerHandle;

/**
 * @author <a href="mailto:yangyong@ufsoft.com.cn">Young Yang</a>
 */

public class EJBTimer implements Timer {

    private EJBTimerTask task;
    private Serializable info;
    private TimerHandle timerHandle;

    public EJBTimer(EJBTimerTask task, Serializable info) {
        this.task = task;
        this.info = info;
        this.timerHandle = new EJBTimerHandler(task.getTimerService().getEjbName(), "" + System.identityHashCode(this));
    }

    public long getTimeRemaining() throws IllegalStateException, NoSuchObjectLocalException, EJBException {
        return (task.scheduledExecutionTime() - System.currentTimeMillis());
    }

    public Date getNextTimeout() throws IllegalStateException, NoSuchObjectLocalException, EJBException {
        return new Date(task.scheduledExecutionTime());
    }

    public Serializable getInfo() throws IllegalStateException, NoSuchObjectLocalException, EJBException {
        return info;
    }

    public TimerHandle getHandle() throws IllegalStateException, NoSuchObjectLocalException, EJBException {
        return timerHandle;
    }

    /**
     * need remove from EJBTimerService's timers
     */
    public void cancel() {
        task.cancel();
    }

    public int hashCode() {
        return task.hashCode();
    }

    public boolean equals(Object obj) {
        if(!(obj instanceof EJBTimer)) {
            return false;
        }
        EJBTimer timer = (EJBTimer) obj;
        return timer.task.equals(task);
    }

    public static void main(String[] args) {

    }
}

