/*
Copyright (C) 1999-2000, contributors of the QuakeForge project

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
// slist.c -- serverlist addressbook

#include "quakedef.h"

server_entry_t	slist[MAX_SERVER_LIST];
/*
static int SList_DownloadProgress( double percent )
{
	static double now, oldtime, newtime;

	cls.download.percent = percent;	

	CL_KeepaliveMessage();	

	newtime = Sys_DoubleTime ();
	now = newtime - oldtime;

	Host_Frame (now);

	oldtime = newtime;

	return cls.download.disconnect; // abort if disconnect received
}

qboolean SList_Download (void)
{
				if( cl_web_download.value && cl_web_download_url.string)
			{				
				char url[1024];
				qboolean success = false;
				char download_tempname[MAX_OSPATH],download_finalname[MAX_OSPATH];
				char folder[MAX_OSPATH];
				char name[MAX_OSPATH];
				extern char server_name[MAX_QPATH];
				extern int net_hostport;



				//Create the FULL path where the file should be written
				Q_snprintfz (download_tempname, MAX_OSPATH, "%s/%s.tmp", com_gamedir, model_precache[i]);
				
				//determine the proper folder and create it, the OS will ignore if already exsists
				COM_GetFolder(model_precache[i],folder);// "progs/","maps/"
				Q_snprintfz (name, sizeof(name), "%s/%s", com_gamedir, folder);		
				
				Sys_mkdir (name);								

				Con_Printf( "Downloading:\nfile: %s\nfrom: %s\n\n", model_precache[i], cl_web_download_url.string);

				//assign the url + path + file + extension we want
				Q_snprintfz( url, sizeof( url ), "%s%s", cl_web_download_url.string, model_precache[i]);
				
				//R00k: fixme! check for trailing forward slash "/" add if not present!!!!
				//Q_snprintfz( url, sizeof( url ), "%s/%s", cl_web_download_url.string, model_precache[i]);

				cls.download.web = true;
				cls.download.disconnect = false;
				cls.download.error = NULL;
				cls.download.percent = 0.0;

				//let libCURL do it's magic!!
				success = Web_Get(url, NULL, download_tempname, false, 600, 30, CL_WebDownloadProgress);				

				cls.download.web = false;

				if ((cls.download.error)||(success == FALSE))
				{
					Con_Printf ("Download Error: %s\n",cls.download.error);
					Con_Printf ("\nThe required file '%s' could not be found at %s.\n", model_precache[i], url);
					remove (download_tempname);
					return;
				}				

				if( cls.download.disconnect )//if the user type disconnect in the middle of the download
				{
					cls.download.disconnect = false;
					CL_Disconnect_f();
					return;
				}				

				if (success)
				{
					Con_Printf("Download succesfull.\n\n");
					//Rename the .tmp file to the final precache filename
					Q_snprintfz (download_finalname, MAX_OSPATH, "%s/%s", com_gamedir, model_precache[i]);					
					rename (download_tempname, download_finalname);
					//R00k: fixme download all required files THEN reconnect...
					Cbuf_AddText (va("connect %s:%u\n",server_name,net_hostport));//reconnect after each success					
					return;
				}
}
*/

void SList_Init (void)
{
	memset (&slist, 0, sizeof(slist));	
}

void SList_Shutdown (void)
{  
	FILE	*f;

	if (!(f = fopen (va("%s/servers.lst", com_basedir), "wt")))
	{
		Con_DPrintf ("Couldn't open servers.lst\n");
		return;
	}
	SList_Save (f);
	fclose (f);
}
			
void SList_Set (int i, char *addr, char *desc)
{
	if (i >= MAX_SERVER_LIST || i < 0)
		Sys_Error ("SList_Set: Bad index %d", i);

	if (slist[i].server)
		Z_Free (slist[i].server);
	if (slist[i].description)
		Z_Free (slist[i].description);

	slist[i].server = CopyString (addr);
	slist[i].description = CopyString (desc);
}

void SList_Reset_NoFree (int i)
{ 
	if (i >= MAX_SERVER_LIST || i < 0)
		Sys_Error ("SList_Reset_NoFree: Bad index %d", i);

	slist[i].description = slist[i].server = NULL;
}

void SList_Reset (int i)
{
	if (i >= MAX_SERVER_LIST || i < 0)
		Sys_Error ("SList_Reset: Bad index %d", i);

	if (slist[i].server)
	{
		Z_Free (slist[i].server);
		slist[i].server = NULL;
	}

	if (slist[i].description)
	{
		Z_Free (slist[i].description);
		slist[i].description = NULL;
	}
}

void SList_Switch (int a, int b)
{
	server_entry_t	temp;

	if (a >= MAX_SERVER_LIST || a < 0)
		Sys_Error ("SList_Switch: Bad index %d", a);
	if (b >= MAX_SERVER_LIST || b < 0)
		Sys_Error ("SList_Switch: Bad index %d", b);

	memcpy (&temp, &slist[a], sizeof(temp));
	memcpy (&slist[a], &slist[b], sizeof(temp));
	memcpy (&slist[b], &temp, sizeof(temp));
}

int SList_Length (void)
{
	int	count;

	for (count = 0 ; count < MAX_SERVER_LIST && slist[count].server ; count++)
		;

	return count;
}

void SList_Load (void)
{
	int	c, len, argc, count;
	char	line[128], *desc, *addr;
	FILE	*f;

	if (!(f = fopen (va("%s/servers.lst", com_basedir), "rt")))
		return;

	count = len = 0;
	while ((c = getc(f)))
	{
		if (c == '\n' || c == '\r' || c == EOF)
		{
			if (c == '\r' && (c = getc(f)) != '\n' && c != EOF)
				ungetc (c, f);

			line[len] = 0;
			len = 0;
			Cmd_TokenizeString (line);

			if ((argc = Cmd_Argc()) >= 1)
			{
				addr = Cmd_Argv(0);
				desc = (argc >= 2) ? Cmd_Args() : "Unknown";
				SList_Set (count, addr, desc);
				if (++count == MAX_SERVER_LIST)
					break;
			}
			if (c == EOF)
				break;	//just in case an EOF follows a '\r'
		}
		else
		{
			if (len + 1 < sizeof(line))
				line[len++] = c;
		}
	}

	fclose (f);
}

void SList_Save (FILE *f)
{
	int	i;

	for (i=0 ; i<MAX_SERVER_LIST ; i++)
	{
		if (!slist[i].server)
			break;

		fprintf (f, "%s\t%s\n", slist[i].server, slist[i].description);
	}
}
