//where I am
#include "R4_HEADER_State.h"
//manager
#include "StateManager.h"
//home
#include "R0_Init_State.h"
//a step after
#include "PacketSemanticAnalyzer.h"

namespace PamOffLineSW
{
R4_HEADER_State R4_HEADER_State::instance;
//extern LogUtil* mainLogUtil;
//extern long int iNumCadres; //cadre's number  
//extern unsigned long long int iByte_tot;// how many bytes I have read till now	
extern bool isCadreGood;//if the cadre is good


R4_HEADER_State::R4_HEADER_State()
{
	headerPKT =NULL;
	pamPKT =NULL;
	pamPKT_length=0;
	posPamPKT=0;
	
	isPKTGood=true;
}

R4_HEADER_State::~R4_HEADER_State()
{
	deleteBufferPKT();
	pamPKT_length=0;
	posPamPKT=0;
		
	isPKTGood=true;
}

void R4_HEADER_State::deleteBufferPKT()
{			
	if(headerPKT)
	{	
		delete[] headerPKT;
		headerPKT =NULL;
	}

	if(pamPKT)
	{	
		delete[] pamPKT;
		pamPKT =NULL;
	}
	
}


void R4_HEADER_State::initBufferPKT(char* headPKT)
{				
	//I have found a Pamela Packet Header
	//I read how many bytes is the packet long
	long int pack_length =  (long int)(unsigned char)(headPKT[14])+
					 256*(long int)(unsigned char)(headPKT[13])+
				 256*256*(long int)(unsigned char)(headPKT[12]);
	
	pamPKT_length=pack_length;
	
	deleteBufferPKT();//just to be sure	
	
	// I will save the Pamela Packet and its header in this buffer
	headerPKT=new char[LENGTH_HEADER_PKT];
	//I start copying on the buffer the Header
	for(int i=0;i<LENGTH_HEADER_PKT;i++)
	{
		headerPKT[i]=headPKT[i];
	}
	// I will save the Pamela Packet without the header in this buffer
	pamPKT=new char[pamPKT_length];
	//zerooo
	for(int i=0;i<pamPKT_length;i++)
	{
		pamPKT[i]=0;
	}
	posPamPKT=0;
	if((!isCadreGood)&&(isPKTGood))
	{
		isPKTGood = false;			
	}
}

void R4_HEADER_State::readInput(char inputbyte)
{				
	//we have identified a Pamela Packet,
	//we add bytes to the buffer untill we reach the total length

	if((!isCadreGood)&&(isPKTGood))
	{
		isPKTGood = false;			
	}

	pamPKT[posPamPKT]=inputbyte;
		
	//if we reach the end of the Packet
	if(posPamPKT==(pamPKT_length-1))
	{
		//we can use the packet
		PacketSemanticAnalyzer::getInstance().managePKT(headerPKT, pamPKT, pamPKT_length, isPKTGood); 	

		//reset isPKTGood to true
		isPKTGood=true;	
		//delete buffer	     
		deleteBufferPKT();
		//reset values
		pamPKT_length=0; posPamPKT=0;
		
		//return to R0 initial state
		StateManager::getInstance().changeState(&R0_Init_State::getInstance());		
	}	
	
	posPamPKT++;
}

}
