#include "StdAfx.h"
//#ifdef OLV_UTILES32
#include "sock_task.h"
#include "olv.h"
#include "olv_limp.h"
#include "olv_limp_thr.h"
#include "olv_reco.h"
#include "olv_reco_thr.h"
#include "sock_sv.h"
#include "utiles_def.h"
//#include "wvarios.h"

Csock_task::Csock_task(COlivia *ol)
{
	olv=ol;
}

Csock_task::~Csock_task(void)
{
}
//*************************************************************************************
void Csock_task::run()
{
	int id, ithr;
	BOOL sal=FALSE;
	BOOL fin_ok=FALSE;
	__int64 t1=_time64(NULL);
	__int64 timeout;
	timeout=20000;//20 seg
	ithr=-1;
	Param_olv_limp_thr pp;
	pp.id_e=0;
	BOOL *pirate=NULL;
#ifndef _DEBUG
	__int64 t2;
#endif

	if(olv->olv_limp)
		pirate=&olv->olv_limp->thr_limp->pirate;
	else if(olv->olv_reco)
		pirate=&olv->olv_reco->thr_limp->pirate;
	if (pirate==NULL)
	{
		pirate=new BOOL();
		*pirate=FALSE;
	}
	do 
	{
#ifndef _DEBUG
		t2 = _time64(NULL);
		if((t2-t1)>=timeout)
		{
			sal=TRUE;
			continue;
		}
#endif
		if(!soc->recibe_package(0))
		{
			Sleep(1);
			continue;
		}
		t1=_time64(NULL);
		
		if(soc->nb<sizeof(int))
		{
			sal=TRUE;
			continue;
		}
		switch(*(int*)soc->buf)
		{
		case PETICION_GENERAL_OK:
			{	
				id=PETICION_GENERAL_OK;
				if(!soc->envia_package((BYTE*)&id,sizeof(int)))
				{
					sal=TRUE;
					continue;
				}
				break;
			}
		case PETICION_GENERAL_PRESENTA:
			{			
				if(soc->nb<2*sizeof(int))
				{
					sal=TRUE;
					continue;
				}
				//pilla ithr, contesta ok
				ithr = ((int*)soc->buf)[1];
				id=PETICION_GENERAL_OK;
				if(!soc->envia_package((BYTE*)&id,sizeof(int)))
				{
					sal=TRUE;
					continue;
				}
				//envía la info de la task
				if(!soc->envia_package((BYTE*)&olv->infotask,sizeof(InfoIniTask)))
				{
					sal=TRUE;
					continue;
				}
				break;
			}
		case PETICION_GENERAL_FIN:
			{
				sal=TRUE;
				if(soc->nb<2*sizeof(int))
				{
					continue;
				}
				if(((int*)soc->buf)[1]==PETICION_GENERAL_OK)
					fin_ok=TRUE;
				id=PETICION_GENERAL_FIN;
				if(!soc->envia_package((BYTE*)&id,sizeof(id)))
				{
					sal=TRUE;
					continue;
				}
				//mira si ok o no
				break;
			}
		case PETICION_GENERAL_DAME_LOG:
			{
				soc->buf[soc->nb-1] = 0;
				olvlog(LOG_TODO,"LogSock",(char*)&((int*)soc->buf)[1]);
				break;
			}
		}		
	} while (!*soc->pirate && !sal && !*pirate_soc && !soc->sock_cerrado && !*pirate);

	if(ithr>=0)
	{
		if(!fin_ok && (sal || soc->sock_cerrado))
		{
			//avisar en encola de que ha ido mal
			pp.id_e=-1;
		}
	}
	else
		pp.id_e=-2;

	if(olv->olv_limp)
		olv->olv_limp->thr_limp->encola(olv->olv_limp->thr_limp->OLV_LIMP_EV_TASK_FIN,&pp,FALSE);
	else if(olv->olv_reco)
		olv->olv_reco->thr_reco->encola(olv->olv_reco->thr_limp->OLV_LIMP_EV_TASK_FIN,&pp,FALSE);
	olvlog(LOG_TODO,"LogSock","Saliendo sock ithr %ld %s", ithr, fin_ok ? "Bien" : "Mal");

}
//#endif