/*
   Copyright (C) 2007 Will Franklin.

   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.

 */

#ifndef _MM_COMMON
#define _MM_COMMON

#include "../qcommon/qcommon.h"
#include "mm_supported.h"
#include "mm_hash.h"

//#define LOCAL_TEST

// old bits of code which i will remove
//#define OLD_GAMESERVER_CHECKING

#define PACKET_PING_TIME 10000 // 10 seconds
#define PACKET_NO_DELIM  4

#define MM_Malloc( size ) Mem_Alloc( mm_mempool, size )
#define MM_Free( data ) Mem_Free( data )

#define MAX_MM_CMD_LEN 64

#define MM_SERVER_VAR "mmserver"
#define MM_SERVER_IP  "217.172.187.143:46002"

#define MM_HEARTBEAT_SECONDS 120

typedef struct mm_packet_s
{
	char *cmd;
	char hash[HASH_SIZE + 1];
	unsigned long int senttime;
	
	struct mm_packet_s *next;
} mm_packet_t;

typedef struct
{
	char *nickname;
	int uid;
	int skill_level;

	netadr_t *address;

#ifdef OLD_GAMESERVER_CHECKING
	int serverping; 
#endif
	int ping; // different from above
	unsigned long int lastack;
	int noack;

	mm_packet_t *packets;
} mm_client_t;

typedef struct mm_ignoreserver_s
{
	char ip[32];
	struct mm_ignoreserver_s *next;
} mm_ignoreserver_t;

typedef struct mm_match_s
{
	// prev and next match for linked list
	struct mm_match_s *prev;
	struct mm_match_s *next;

	qboolean open;

	// stores connected client addresses
	mm_client_t *clients[MAX_CLIENTS];
	int maxclients;
	int fakeuid;

	mm_type_t ping_type;

	int gametype;

	int skill_level;
	mm_type_t skill_type;

	unsigned long int lastping;

	// time when the match began waiting for a server
	unsigned long int awaitingserver;

	mm_ignoreserver_t *ignores;
} mm_match_t;

// for compatibility with mm_common functions.
typedef struct
{
	struct mm_match_s *first;
	struct mm_match_s *last; // not used atm

} mm_matchlist_t;

extern mempool_t *mm_mempool;
// for compatibility with mm_common functions.
extern mm_matchlist_t *matchlist;

//===============
// mm_common.c
//===============
void          MM_FreeClient( mm_client_t *client );
void          MM_FreeMatch( mm_match_t *match );
int           MM_ClientCount( const mm_match_t *match );
mm_client_t **MM_FindClientByUserId( mm_match_t *match, const int uid );
mm_client_t **MM_FindClientByAddress( mm_match_t *match, const netadr_t *address );
void          MM_SendMsgToServer( const socket_t *socket, const char *format, ... );

#endif
