package ch.frankel.blog.vaadin;

import java.util.Random;

import org.vaadin.artur.icepush.ICEPush;

import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Window;

public class PushApplication extends Application {

    /** Class serial version unique identifier. */
    private static final long serialVersionUID = 1L;

    private ICEPush push = new ICEPush();

    private Random random = new Random();

    private boolean shouldUpdate;

    @Override
    public void init() {

        Window mainWindow = new Window("Push Application Example");

        mainWindow.addComponent(push);

        Button startButton = new Button("Start");

        mainWindow.addComponent(startButton);

        startButton.addListener(ClickEvent.class, this, "startUpdate");

        Button stopButton = new Button("Stop");

        mainWindow.addComponent(stopButton);

        stopButton.addListener(ClickEvent.class, this, "stopUpdate");

        setMainWindow(mainWindow);

        new ComputeThread().start();
    }

    private class ComputeThread extends Thread {

        @Override
        public void run() {

            while (true) {

                if (shouldUpdate) {

                    Label label = new Label();

                    label.setValue(random.nextInt(1000));

                    getMainWindow().addComponent(label);

                    push.push();
                }

                try {

                    Thread.sleep(5000);

                } catch (InterruptedException e) {

                    // NOTHING TO DO
                }
            }
        }
    }

    public void startUpdate(ClickEvent event) {

        shouldUpdate = true;

        System.out.println("Start update");
    }

    public void stopUpdate(ClickEvent event) {

        shouldUpdate = false;

        System.out.println("Stop update");
    }
}
