#include "p_apps.h"
#include "v_task.h"
#include "page12.h"

#include <reg52.h>

BOOLEAN PIO_bHandsetUp;

XCHAR Task_iDnsType = DNS_TYPE_NONE;

void Ac97Stop()
{
}

void OnLogoff()
{
	if (PPPoE_bInUse)
	{
		DisplayString(g_cPPPoE, 0);
		DisplayString(g_cDisconnecting, 1);
		PPPoEDisconnect();
	}
	UdpDebugUpdate();
}

void OnPage12End()
{
	OnLogoff();
	EA = 0;		// disable all interrupts
	DisplayStatus(g_cBooting, 255, 8);
//	Ne2000Initialize_Step1();
//	SysSleep(1000000);
	Ne2000Initialize_Step2();
	SwitchPage(6);	// continue to load g.729
}


void TaskInitialize()
{
	DSHORT iPort = HTTP_SERVER_PORT;

	UpgradeInitialize();
	HttpGetIPInitialize();

	DisplayString("Get Public IP", 0);

	p_memset_ip_0(Sys_pProxyServerIP);

	if (!p_strlen_x(Sys_pNatAddr))
	{
		CheckIPFromStoredDns();
		return;
	}

	iPort = ParseDnsAddr(Sys_pNatAddr, Sys_pProxyServerIP, (PXCHAR)Sdram_pDataCache);
	if (iPort)
	{
		Sys_iNatPort = iPort;
	}
	if (IsValidIP(Sys_pProxyServerIP))
	{
		if (IsPublicIP(Sys_pProxyServerIP))
		{
			OnPage12End();
		}
		else
		{
			CheckIPFromStoredDns();
		}
	}
	else
	{
		Task_iDnsType = DNS_TYPE_PROXY;
		DnsSend((PXCHAR)Sdram_pDataCache, FALSE);
	}
}


void TaskSignalMsg(UCHAR iType)
{
	switch (iType)
	{
	case SIGNAL_IP_CONFLICT:
		DisplayString(g_cDuplicatedIP, 0);
		SysSleep(5000000);
		break;

	case SIGNAL_DHCP_FAILED:
		OnPage12End();
		break;
	}
}

void TaskHandleTimer()
{
	UpgradeHandleTimer();
	HttpGetIPHandleTimer();
}

void TaskDnsCompleted()				
{
	DCHAR iType;

	iType = Task_iDnsType;
	Task_iDnsType = DNS_TYPE_NONE;

	switch (iType)
	{
	case DNS_TYPE_PROXY:
		p_memcpy_ip(Sys_pProxyServerIP, Dns_pResolvedIP);
		if (IsPublicIP(Sys_pProxyServerIP))
		{
			CheckIPStart(Sys_pProxyServerIP, Sys_iNatPort);
		}
		else
		{
			CheckIPFromStoredDns();
		}
		break;
	}
}
			
void TaskDnsFailed()				
{
	DCHAR iType;

	iType = Task_iDnsType;
	Task_iDnsType = DNS_TYPE_NONE;

	OutputString(IDS_DNS_FAILED);

	switch (iType)
	{
	case DNS_TYPE_PROXY:
		CheckIPFromStoredDns();
		break;
	}
}

void TaskWaitPacket()
{
	SysSleep(p_rand()&1023);
}

void TaskSendPacket(USHORT iLen, PXCHAR pPacket)
{
	Ne2000Send(iLen, pPacket);
}

BOOLEAN	TaskRunTcp()
{
	if (UpgradeRun())		return TRUE;
	if (HttpGetIPRun())	return TRUE;
	return FALSE;
}

BOOLEAN TaskRunUdp()
{
	// Unknown udp data, ignore
	return FALSE;
}

