package siprp.lembretes;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class LembretesDemon extends Thread
{

	private static final long SLEEP_TIME_MILLIS = 60 * 60 * 1000; // one hour
	
	private static boolean isRunning = false;
	
	private static LembretesDemon instance = null;
	
	private LembretesDataProvider lembretesProvider = null;
	
	private boolean doneForToday = false;
	
	private Calendar lastIteration = Calendar.getInstance();
	
	private LembretesDemon()
	{
		try
		{
			lembretesProvider = new LembretesDataProvider();
		} catch( Exception e )
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * Instanciates and starts a LembretesDemon
	 */
	public static void go()
	{
		getInstance();
		startDemon();
	}
	
	/**
	 * Gets LembretesDemon
	 * @return
	 */
	public static LembretesDemon getInstance()
	{
		if( LembretesDemon.instance == null )
		{
			LembretesDemon.instance = new LembretesDemon();
		}
		return LembretesDemon.instance;
	}
	
	public static void stopDemon()
	{
		if( LembretesDemon.isRunning )
		{
			LembretesDemon.isRunning = false;
		}
	}
	
	public static void startDemon()
	{
		if( !LembretesDemon.isRunning )
		{
			LembretesDemon.isRunning = true;
			instance.start();
		}
	}
	
	@Override
	public void run()
	{
		System.out.println( new Date() + ": Starting LembretesDemon" );
		while( isRunning )
		{
			try
			{
				Calendar now = Calendar.getInstance();
				if( !doneForToday || lastIterationWasYesterday( now ) )
				{
					doStuff();
					doneForToday = true;
				}
				lastIteration = now;
				Thread.sleep( SLEEP_TIME_MILLIS );
			} catch( InterruptedException e )
			{
				e.printStackTrace();
			}
		}
		System.out.println( new Date() + ": Stopping LembretesDemon" );
	}
	
	private void doStuff()
	{
		List<Integer> fichasExpiradas = lembretesProvider.getFichasExpiradasID();
		lembretesProvider.createLembretesForFichas( fichasExpiradas );
	}
	
	private boolean lastIterationWasYesterday( Calendar now )
	{
		return ( now.get( Calendar.DAY_OF_MONTH ) > lastIteration.get( Calendar.DAY_OF_MONTH ) )
		||
		( now.get( Calendar.DAY_OF_MONTH ) == 1 && lastIteration.get( Calendar.DAY_OF_MONTH ) != 1 );
	}
}
