#include "RBC9-SpaceNav.h"


#pragma warning(disable : 4996)

VOID RBC9_SEQ_Init_HID(IN PDEVICE_OBJECT pDev_obj)
{
	RBC9_Led_Queue_Delete(pDev_obj);
	RBC9_Led_Queue_Add(pDev_obj,2000,500,250);
	RBC9_Led_Queue_Add(pDev_obj,2000,300,150);
	RBC9_Led_Queue_Add(pDev_obj,2000,200,100);

}

VOID RBC9_SEQ_Special_Action(IN PDEVICE_OBJECT pDev_obj)
{
	RBC9_Led_Queue_Delete(pDev_obj);
	RBC9_Led_Queue_Add(pDev_obj,5000,100,500);
}

VOID RBC9_SEQ_Special_Action_Fin(IN PDEVICE_OBJECT pDev_obj)
{
	RBC9_Led_Queue_Delete(pDev_obj);
	RBC9_Led_Queue_Add(pDev_obj,2000,50,100);
}

VOID RBC9_SEQ_Change_Profil(IN PDEVICE_OBJECT pDev_obj)
{
	RBC9_Led_Queue_Delete(pDev_obj);
	RBC9_Led_Queue_Add(pDev_obj,1000,50,10);

}
VOID RBC9_Led_Clignote(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION		pDevExt;
	ULONGLONG				cur_time;
	PLED_REPEAT				NextLed;

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	cur_time = KeQueryInterruptTime();

	if(cur_time > pDevExt->Led->next_time)
	{

		//	DBG_ENTER((""));

		if(pDevExt->Led->first_time == 0)
		{
			pDevExt->Led->first_time = cur_time;
		}

		if (pDevExt->Led->first_time + (pDevExt->Led->HowLong * 10 * 1000) < cur_time)
		{
			NextLed = pDevExt->Led->NextLed;

			if(pDevExt->Led->NextLed != NULL)
			{
				pDevExt->Led->NextLed->On = pDevExt->Led->On;
			}

			ExFreePool(pDevExt->Led);

			pDevExt->Led = NextLed;

			//DBG_LEAVE(("Fin de sequence"));
			RBC9_nav_led(pDev_obj,TRUE);
			return;
		}


		pDevExt->Led->On = !pDevExt->Led->On;

		RBC9_nav_led(pDev_obj,pDevExt->Led->On);

		pDevExt->Led->next_time = cur_time + ((pDevExt->Led->On) ? pDevExt->Led->TimeOn:pDevExt->Led->TimeOff) * 10 * 1000;



		//	DBG_LEAVE((""));
	}

}

VOID RBC9_Led_Queue_Delete(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION	pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	PLED_REPEAT			FirstLed;
	PLED_REPEAT			NextLed;

	//DBG_ENTER((""));

	FirstLed=pDevExt->Led;
	pDevExt->Led = NULL;

	while(FirstLed !=NULL)
	{
		NextLed = FirstLed->NextLed;

		//DBG_OUT(("Delete Led"));

		ExFreePool(FirstLed);

		FirstLed = NextLed;

	}

	//DBG_LEAVE((""));
}


VOID RBC9_Led_Queue_Add(IN PDEVICE_OBJECT pDev_obj,int HowLong,int TimeOn,int TimeOff)
{
	PDEVICE_EXTENSION	pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	PLED_REPEAT			NewLed=(PLED_REPEAT)  ExAllocatePool(NonPagedPool, sizeof(LED_REPEAT));

	PLED_REPEAT			NextLed;
	PLED_REPEAT			LastLed;

	//	DBG_ENTER((""));

	if (NewLed == NULL)
	{
		DBG_LEAVE(("ExAllocatePool Error"));
		return;
	}
	RtlZeroMemory(NewLed, sizeof(LED_REPEAT));


	if (pDevExt->Led == NULL)
	{

		pDevExt->Led = NewLed;
	}
	else
	{
		NextLed = pDevExt->Led->NextLed;
		LastLed = pDevExt->Led;

		while (NextLed != NULL)
		{
			LastLed = NextLed;
			NextLed = LastLed->NextLed;
		}

		LastLed->NextLed = NewLed;
	}

	NewLed->On = 0;
	NewLed->first_time = 0;
	NewLed->next_time = 0;
	NewLed->HowLong = HowLong;
	NewLed->TimeOn = TimeOn;
	NewLed->TimeOff = TimeOff;




	//DBG_LEAVE((""));

}