#include "raid_agent.h"

#define TIME_TEN_SECOND 10
#define TIME_ONE_MINUTE 60
#define TIME_TEN_MINUTE (60*10)
#define TIME_ONE_QUARTER (60*15)
#define TIME_HALF_HOUR (60*30)
#define TIME_ONE_HOUR (60*60)
#define TIME_ONE_DAY (60*60*24)

static unsigned long tensec_countdown;
static unsigned long minute_countdown;
static unsigned long tenmin_countdown;
static unsigned long quarter_countdown;
static unsigned long halfhour_countdown;
static unsigned long hour_countdown;
static unsigned long day_countdown;
static unsigned long prev_time;
static unsigned long next_time;

extern int raid_update_system();


int raid_agent_task_init()
{
	time_t l_time;
	struct tm *t;
	int hour,minute,second;
	
	l_time=time(NULL);
	t=localtime(&l_time);
	hour=t->tm_hour;
	minute=t->tm_min;
	second=t->tm_sec;
	
	tensec_countdown=second%TIME_TEN_SECOND;
	minute_countdown=second%TIME_ONE_MINUTE;
	tenmin_countdown=(minute*TIME_ONE_MINUTE + second)%TIME_TEN_MINUTE;
	quarter_countdown=(minute*TIME_ONE_MINUTE + second)%TIME_ONE_QUARTER;
	halfhour_countdown=(minute*TIME_ONE_MINUTE + second)%TIME_HALF_HOUR;
	hour_countdown=(minute*TIME_ONE_MINUTE + second)%TIME_ONE_HOUR;
	day_countdown=(hour*TIME_ONE_HOUR + minute*TIME_ONE_MINUTE + second)%TIME_ONE_DAY;
	
	prev_time=next_time=l_time;
	return 1;
}

int raid_agent_task_timer()
{
	unsigned long time_past;
	
	next_time=time(NULL);
	time_past=next_time-prev_time;
	
	tensec_countdown+=time_past;
	minute_countdown+=time_past;
	tenmin_countdown+=time_past;
	quarter_countdown+=time_past;
	halfhour_countdown+=time_past;
	hour_countdown+=time_past;
	day_countdown+=time_past;	
	
	if(tensec_countdown >= TIME_TEN_SECOND)
	{
		time_past=tensec_countdown-TIME_TEN_SECOND;
		tensec_countdown=time_past;
		//Call ten-sec clock function here
	}
	
	if(minute_countdown >= TIME_ONE_MINUTE)
	{
		time_past=minute_countdown-TIME_ONE_MINUTE;
		minute_countdown=time_past;
		//Call minute clock function here
		raid_update_system();
	}
	
	if(tenmin_countdown >= TIME_TEN_MINUTE)
	{
		time_past=tenmin_countdown-TIME_TEN_MINUTE;
		tenmin_countdown=time_past;
		//Call ten-min clock function here
	}
	
	if(quarter_countdown >= TIME_ONE_QUARTER)
	{
		time_past=quarter_countdown-TIME_ONE_QUARTER;
		quarter_countdown=time_past;
		//Call quarter clock function here
	}
	
	if(halfhour_countdown >= TIME_HALF_HOUR)
	{
		time_past=halfhour_countdown-TIME_HALF_HOUR;
		halfhour_countdown=time_past;
		//Call half-hour clock function here
	}
	
	if(hour_countdown >= TIME_ONE_HOUR)
	{
		time_past=hour_countdown-TIME_ONE_HOUR;
		hour_countdown=time_past;
		//Call hour clock function here
	}
	
	if(day_countdown >= TIME_ONE_DAY)
	{
		time_past=day_countdown-TIME_ONE_DAY;
		day_countdown=time_past;
		//call day clock function here
	}
	
	prev_time=next_time;
	return 1;
}
