package org.ajax4jsf.bean;

import java.util.Date;
import java.util.EventListener;
import java.util.EventObject;

import org.ajax4jsf.event.PushEventListener;

public class AjaxPushTestBean implements Runnable {

    private boolean enabled = false;

    private Date startDate;

    private PushEventListener listener;

    private Thread thread;

    private int eventsSent = 0;

    private String content = "content";

    /**
     * Gets value of content field.
     * @return value of content field
     */
    public String getContent() {
        return content;
    }

    /**
     * Set a new value for content field.
     * @param content a new value for content field
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * Gets value of eventsSent field.
     * @return value of eventsSent field
     */
    public int getEventsSent() {
        return eventsSent;
    }

    /**
     * Set a new value for eventsSent field.
     * @param eventsSent a new value for eventsSent field
     */
    public void setEventsSent(int eventsSent) {
        this.eventsSent = eventsSent;
    }

    public void addListener(EventListener listener) {
        synchronized (listener) {
            if (this.listener != listener) {
                this.listener = (PushEventListener) listener;
            }
        }
    }

    public void run() {
        while (thread != null) {
            try {
                long left = System.currentTimeMillis() - startDate.getTime();
                if (left >= 60000) {
                    stop();
                }
                listener.onEvent(new EventObject(this));
                eventsSent++;
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void start() {
        if (thread == null) {
            thread = new Thread(this);
            thread.setDaemon(true);
            thread.start();
            startDate = new Date();
            setEnabled(true);
        }
    }

    public void stop() {
        if (thread != null) {
            startDate = null;
            eventsSent = 0;
            setEnabled(false);
            thread = null;
        }
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public void restart() {
        stop();
        start();
    }
}
