package com.example;

import com.vaadin.server.VaadinRequest;

import com.vaadin.annotations.Push;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;

import java.time.Instant;

@Push
public class VaadinPushTest extends UI
{

	Label label = new Label( "Now : " );

	@Override
	protected void init ( VaadinRequest vaadinRequest )
	{
		// Put a widget on this UI. In real work we would use a Layout.
		setContent( this.label );

		// Start the data feed thread
		new FeederThread().start();
	}

	public void tellTime () {
		label.setValue( "Now : " + Instant.now() );
	}

	class FeederThread extends Thread {

		int count = 0;

		@Override
		public void run () {
			try {
				// Update the data for a while
				while ( count < 10000 ) {
					Thread.sleep( 1000 );

					if (getSession() != null) {
						access(() -> {
							count++;
							tellTime();
						});
					}
				}

				// Inform that we have stopped running
				if (getSession() != null) {
					access(() -> label.setValue("Done."));
				}
			} catch ( InterruptedException e ) {
				e.printStackTrace();
			}
		}
	}
}
