#include "doomtype.h"
#include "doomstat.h"
#include "d_player.h"
#include "p_local.h"
#include "sv_main.h"
#include "c_console.h"

#define MASTERPORT 15100


netadr_t  masteraddr; // address of the master server
char      masterip[] = "csdoom.dhs.org";
//char      masterip[] = "127.0.0.1";
buf_t     ml_message;
byte      ml_message_buffer[MAX_UDP_PACKET];

char      wadname[32];
bool      pwad;

CVAR (master, "1", CVAR_SERVERINFO);
CVAR (hostname, "Unnamed", CVAR_ARCHIVE);
CVAR (fragstats, "No", CVAR_ARCHIVE);

bool masterupdate;

//
// SV_InitMaster
//
void SV_InitMaster(void)
{
	NET_StringToAdr (masterip, &masteraddr);

	I_SetPort(masteraddr, MASTERPORT);

	ml_message.data = ml_message_buffer;
	ml_message.maxsize = sizeof(ml_message_buffer);
}


//
// SV_UpdateMaster
//
void SV_UpdateMaster(void)
{
	if (!master.value)
		return;

	// update masteraddr every 3 hours
	if ((gametic % (TICRATE*60*180) ) == 0)
	{
		NET_StringToAdr (masterip, &masteraddr);
		I_SetPort(masteraddr, MASTERPORT);
	}

	if ((gametic % (TICRATE*25)) && !masterupdate)
		return;

	masterupdate = false;

	SZ_Clear(&ml_message);
	MSG_WriteLong(&ml_message, CHALLENGE);
	NET_SendPacket(ml_message.cursize, ml_message.data, masteraddr);
}

//
// SV_SendServerInfo
// Sends server info to a launcher
//
void SV_SendServerInfo()
{
	int numclients = 0;
	int numplayers = 0;
	int i;

	for (i=0; i<MAXPLAYERS; i++)
		if (clients[i].cls >= cs_connected)
			numclients++;

	SZ_Clear(&ml_message);
	MSG_WriteLong(&ml_message, CHALLENGE);

	MSG_WriteString(&ml_message, (char *)hostname.string);
	
	MSG_WriteByte(&ml_message, numclients);
	MSG_WriteByte(&ml_message, maxclients);

	MSG_WriteString(&ml_message, level.mapname);
	
	if (!pwad)
		MSG_WriteByte(&ml_message, 0);
	else
	{
		MSG_WriteByte(&ml_message, 1);
		MSG_WriteString(&ml_message, wadname);
	}

	MSG_WriteByte(&ml_message, (byte)deathmatch.value);
	MSG_WriteByte(&ml_message, (byte)gameskill.value);
	MSG_WriteByte(&ml_message, (byte)teamplay.value);
	MSG_WriteString(&ml_message, (char *)fragstats.string);

	MSG_WriteLong(&ml_message, dmflags);
	
	for (i=0; i<MAXPLAYERS; i++)
		if (clients[i].cls == cs_spawned)
			numplayers++;

	MSG_WriteByte(&ml_message, numplayers);
			
	for (i=0; i<MAXPLAYERS; i++)
	{
		if (clients[i].cls != cs_spawned)
			continue;

		MSG_WriteString(&ml_message, players[i].userinfo.netname);
		MSG_WriteShort(&ml_message, players[i].fragcount);
		MSG_WriteShort(&ml_message, int(players[i].ping / 35.0 * 1000) );
	}

	NET_SendPacket(ml_message.cursize, ml_message.data, net_from);
}