//========= Copyright © 1996-2005, Sander Corporation, All rights reserved. ============//
//
// Purpose: 
//
// $NoKeywords: $
//=============================================================================//

#include "cbase.h"
#include "hl2wars/mp/gameroom_window.h"
//#include <vgui/IVGui.h>

#include "vgui_controls/CheckButton.h"
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/Controls.h>
#include <vgui/isurface.h>

// chat stuff
#include "iclientmode.h"
#include <vgui/ILocalize.h>

#include "c_playerresource.h"
#include "hl2wars/c_rts_globalresource.h"
#include "hl2wars/c_hl2wars_player.h"
#include "hl2wars/c_util_hl2wars.h"

#include <KeyValues.h>
#include <filesystem.h>

// memdbgon must be the last include file in a .cpp file!!! 
#include "tier0/memdbgon.h"

CGameRoomWindow *g_RoomWindow;

#define BLACK_BAR_COLOR	Color(0, 0, 0, 196)

#define TREE_TEXT_COLOR		Color( 200, 255, 200, 255 )
#define LIST_TEXT_COLOR		TREE_TEXT_COLOR


// ##################################################################################
//	>> Chat functions
//
// ##################################################################################

//-----------------------------------------------------------------------------
// Purpose: The prompt and text entry area for chat messages
//-----------------------------------------------------------------------------
#ifndef _XBOX
CBaseChatInputLine::CBaseChatInputLine( CGameRoomWindow *parent, char const *panelName ) : 
	vgui::Panel( parent, panelName )
{
	//SetMouseInputEnabled( false );
	m_pPrompt = new vgui::Label( this, "ChatInputPrompt", L"Enter text:" );

	m_pInput = new CBaseChatEntry( this, "ChatInput", parent );	
	m_pInput->SetMaximumCharCount( 127 );
}

void CBaseChatInputLine::ApplySchemeSettings(vgui::IScheme *pScheme)
{
	BaseClass::ApplySchemeSettings(pScheme);
	
	// FIXME:  Outline
	vgui::HFont hFont = pScheme->GetFont( "Trebuchet18" );

	m_pPrompt->SetFont( hFont );
	m_pInput->SetFont( hFont );

	SetPaintBackgroundEnabled( false );
	m_pPrompt->SetPaintBackgroundEnabled( false );
	m_pPrompt->SetContentAlignment( vgui::Label::a_west );
	m_pPrompt->SetTextInset( 2, 0 );

#ifdef HL1_CLIENT_DLL
	m_pInput->SetBgColor( Color( 255, 255, 255, 0 ) );
#else
	m_pInput->SetFgColor( GetFgColor() );
	m_pInput->SetBgColor( Color( 20, 20, 20, 128 ) );
#endif

}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseChatInputLine::SetPrompt( const wchar_t *prompt )
{
	Assert( m_pPrompt );
	m_pPrompt->SetText( prompt );
	InvalidateLayout();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseChatInputLine::ClearEntry( void )
{
	Assert( m_pInput );
	SetEntry( L"" );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseChatInputLine::SetEntry( const wchar_t *entry )
{
	Assert( m_pInput );
	Assert( entry );

	m_pInput->SetText( entry );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseChatInputLine::GetMessageText( wchar_t *buffer, int buffersizebytes )
{
	m_pInput->GetText( buffer, buffersizebytes);
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseChatInputLine::PerformLayout()
{
	BaseClass::PerformLayout();

	int wide, tall;
	GetSize( wide, tall );

	int w,h;
	m_pPrompt->GetContentSize( w, h); 
	m_pPrompt->SetBounds( 0, 0, w, tall );

	m_pInput->SetBounds( w + 2, 0, wide - w - 2 , tall );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
vgui::Panel *CBaseChatInputLine::GetInputPanel( void )
{
	return m_pInput;
}

#endif //_XBOX

// ##################################################################################
//	>> The game room panel. Here we place all panels on.
//
// ##################################################################################
CGameRoomWindow::CGameRoomWindow( IViewPort *pViewPort ) : Frame( NULL, PANEL_GAMEROOM )
{
	g_RoomWindow = this;

	// initialize dialog
	m_pViewPort = pViewPort;

	//vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFile("resource/SourceScheme.res", "SourceScheme");
	vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFile("resource/GameLobbyScheme.res", "GameLobbyScheme");
	SetScheme( scheme );
	//CenterThisPanelOnScreen();//keep in mind, hl2 supports widescreen 
	SetVisible(false);//made visible on command later 

	//SetKeyBoardInputEnabled(false);
	//SetMouseInputEnabled(true);

	//Other useful options
	SetMoveable(false);
	SetSizeable(false);
	SetProportional(true);
	SetTitleBarVisible( false );

	// -- set up chat stuff
	m_nMessageMode = MM_SAY;

	m_pLaunchGame = new vgui::Button( this, "GRLaunchGame", "Launch game", this, "GRLaunchGame" );

	m_pChatBox = new TextEntry( this, "ChatBox" );
	m_pChatBox->SetVisible( true );
	m_pChatBox->SetPaintBackgroundEnabled( true );
	m_pChatBox->SetPaintBorderEnabled( true );
	m_pChatBox->SetEnabled( false );

	m_pChatInput = new CBaseChatInputLine( this, "ChatInputLine" );
	m_pChatInput->SetVisible( true );

	// player list stuff
	m_pPlayerList = new CPlayerList( this );

	// create map selector
	m_pMapSelector = new CMapSelector( this );

	// load the control settings
	LoadControlSettings("Resource/UI/GameRoomWindow.res");
} 

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameRoomWindow::ApplySchemeSettings( IScheme *pScheme )
{
	BaseClass::ApplySchemeSettings( pScheme );

	vgui::HFont hFont = pScheme->GetFont( "Trebuchet18" );
	m_pChatBox->SetFont( hFont );

	//m_pSelectedMap->SetFont( hFont );

	m_pChatBox->SetMultiline( true );
	m_pChatBox->SetEditable( false );

	//SetBgColor( Color( 150, 150, 150, 220 ) );
	//SetFgColor( Color( 150, 150, 150, 220 ) );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameRoomWindow::Reset( void )
{

}

//--------------------------------------------------------------------------------------------------------------
void CGameRoomWindow::SetData(KeyValues *data)
{

}

//--------------------------------------------------------------------------------------------------------------
void CGameRoomWindow::ShowPanel( bool bShow )
{
	if ( BaseClass::IsVisible() == bShow )
		return;

	m_pViewPort->ShowBackGround( bShow );

	if ( bShow )
	{
		Activate();
		SetMouseInputEnabled( true );
	}
	else
	{
		SetVisible( false );
		SetMouseInputEnabled( false );
	}
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameRoomWindow::OnCommand(const char *command) 
{ 
	if ( FStrEq( command, "GRLaunchGame" ) )
	{
		Msg("We want to launch the game \n");

		engine->ClientCmd("gr_launchgame");
	}

} 

//--------------------------------------------------------------------------------------------------------------
void CGameRoomWindow::OnThink()
{
	if( !g_RTSR )
		return;
}

//--------------------------------------------------------------------------------------------------------------
void CGameRoomWindow::Update( void )
{

}

//-----------------------------------------------------------------------------
// Purpose: Chat stuff follows here
//-----------------------------------------------------------------------------

void CGameRoomWindow::Send( void )
{
#ifndef _XBOX
	wchar_t szTextbuf[128];

	m_pChatInput->GetMessageText( szTextbuf, sizeof( szTextbuf ) );
	
	char ansi[128];
	g_pVGuiLocalize->ConvertUnicodeToANSI( szTextbuf, ansi, sizeof( ansi ) );

	int len = Q_strlen(ansi);

	/*
This is a very long string that I am going to attempt to paste into the cs hud chat entry and we will see if it gets cropped or not.
	*/

	// remove the \n
	if ( len > 0 &&
		ansi[ len - 1 ] == '\n' )
	{
		ansi[ len - 1 ] = '\0';
	}

	if( len > 0 )
	{
		char szbuf[144];	// more than 128
		//Q_snprintf( szbuf, sizeof(szbuf), "%s \"%s\"", m_nMessageMode == MM_SAY ? "say_gr" : "say_team_gr", ansi );
		Q_snprintf( szbuf, sizeof(szbuf), "%s \"%s\"", m_nMessageMode == MM_SAY ? "say" : "say_team", ansi );

		engine->ClientCmd(szbuf);
	}
	
	m_pChatInput->ClearEntry();
#endif
}

void CGameRoomWindow::ChatPrintf( int iPlayerIndex, int iFilter, const char *fmt, ... )
{
	va_list marker;
	char msg[4096];

	va_start(marker, fmt);
	Q_vsnprintf(msg, sizeof( msg), fmt, marker);
	va_end(marker);

	/*player_info_t sPlayerInfo;
	if ( iPlayerIndex == 0 )
	{
		Q_memset( &sPlayerInfo, 0, sizeof(player_info_t) );
		Q_strncpy( sPlayerInfo.name, "Console", sizeof(sPlayerInfo.name)  );	
	}
	else
	{
		engine->GetPlayerInfo( iPlayerIndex, &sPlayerInfo );
	}	*/

	m_pChatBox->GotoTextEnd();
	m_pChatBox->InsertString(msg);
}

//-----------------------------------------------------------------------------
// Purpose: Receive map info 
//-----------------------------------------------------------------------------
void CGameRoomWindow::GRMapList( bf_read &msg )
{
	char szString[2048];
	msg.ReadString( szString, sizeof(szString) );
	m_pMapSelector->AddMapToList( szString );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameRoomWindow::GRMapInfo( bf_read &msg )
{
	char szString[2048];

	msg.ReadString( szString, sizeof(szString) );
	m_pMapSelector->SetMapPlayers(szString);

	Vector position;
	for(int i = 0; i < MAX_TEAMS_ID_RTS; i++ )
	{
		 m_pMapSelector->SetPosAvailable(i, msg.ReadByte());
		 msg.ReadBitVec3Coord(position);
		 //Msg("%d, position: %f %f %f\n", i, position.x, position.y, position.z );
		 m_pMapSelector->SetPositionOrigin(i, position );
	}

	msg.ReadString( szString, sizeof(szString) );
	m_pMapSelector->SetMapName(szString);
}

//-----------------------------------------------------------------------------
// Purpose: Map list
//-----------------------------------------------------------------------------
CMapSelector::CMapSelector( vgui::Panel *parent ) : BaseClass( parent, "mapselector" )
{
	SetParent(parent);
	//vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFile("resource/SourceScheme.res", "SourceScheme");
	//SetScheme( scheme );
	SetVisible(false);//made visible on command later 

	m_pSelected = NULL;

	//vgui::ivgui()->AddTickSignal( GetVPanel(), 100 );

	vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFile("resource/GameLobbyScheme.res", "GameLobbyScheme");

	// create the list panel
	pMapList = new vgui::ListPanel( this, "maplist");
	pMapList->SetScheme( scheme );
	pMapList->SetMultiselectEnabled( false );
	pMapList->AddColumnHeader( 0, "name", "Missions", 200, ListPanel::COLUMN_RESIZEWITHWINDOW );
	pMapList->SetFont( vgui::scheme()->GetIScheme(GetScheme())->GetFont( "DefaultSmall" ) );

	m_nMapTextureID = -1;

	m_pMapName = vgui::SETUP_PANEL(new vgui::Label(this,"MapName","Name: None"));		
	m_pMapName->SetScheme(vgui::scheme()->LoadSchemeFromFile("resource/ClientScheme.res", "ClientScheme"));	//Set it's scheme...
	m_pMapName->SetBgColor(Color(0,0,0,0));	//Translucent BG
	m_pMapName->SetPaintBackgroundEnabled( false );
	m_pMapName->SetPaintBorderEnabled( false );	
	m_pMapName->SetContentAlignment( vgui::Label::a_west );

	m_pPlayers = vgui::SETUP_PANEL(new vgui::Label(this,"Players","Players: None"));		
	m_pPlayers->SetScheme(vgui::scheme()->LoadSchemeFromFile("resource/ClientScheme.res", "ClientScheme"));	//Set it's scheme...
	m_pPlayers->SetBgColor(Color(0,0,0,0));	//Translucent BG
	m_pPlayers->SetPaintBackgroundEnabled( false );
	m_pPlayers->SetPaintBorderEnabled( false );	
	m_pPlayers->SetContentAlignment( vgui::Label::a_west );

	// init position buttons images
	m_pImagesPositions[0].Init( GetVPanel(), "VGUI/buttons/position_one.vmt");
	m_pImagesPositions[1].Init( GetVPanel(), "VGUI/buttons/position_two.vmt");
	m_pImagesPositions[2].Init( GetVPanel(), "VGUI/buttons/position_three.vmt");
	m_pImagesPositions[3].Init( GetVPanel(), "VGUI/buttons/position_four.vmt");
	m_pImagesPositions[4].Init( GetVPanel(), "VGUI/buttons/position_five.vmt");
	m_pImagesPositions[5].Init( GetVPanel(), "VGUI/buttons/position_six.vmt");
	m_pImagesPositions[6].Init( GetVPanel(), "VGUI/buttons/position_seven.vmt");
	m_pImagesPositions[7].Init( GetVPanel(), "VGUI/buttons/position_eight.vmt");
	m_pImagesPositions[8].Init( GetVPanel(), "VGUI/buttons/position_blank.vmt");

	// create position buttons
	for( int i = 0; i < MAX_TEAMS_ID_RTS; i++ )
	{
		char command[144];
		Q_snprintf( command, sizeof(command), "bposition_%d", i );

		m_pPositions[i] = new CBitmapButtonRTS( this, "button_position", ""); 
		m_pPositions[i]->SetVisible( false );
		m_pPositions[i]->SetParent(this);
		m_pPositions[i]->AddActionSignalTarget(this);
		m_pPositions[i]->SetCommand(command);
		m_pPositions[i]->AddButtonFlags(F_ONEIMAGE);
	}

	m_MapCenter = Vector2D( 512, 512 );
	m_fMapScale = 1.0f;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::ActionPosition( int position )
{
	C_HL2Wars_Player* pPlayer = C_HL2Wars_Player::GetLocalHL2WarsPlayer();
	if( !pPlayer )
		return;		

	if( g_RTSR->GetPosition( pPlayer->GetSlot() )  == position )
	{
		char szbuf[144];	// more than 128
		Q_snprintf( szbuf, sizeof(szbuf), "gr_requestposition -1 %d", pPlayer->GetSlot() );

		engine->ClientCmd( szbuf );	
	}
	else if( pPlayer == g_RTSR->GetGameMaster() && !g_RTSR->IsPositionFree(position) )
	{
		for( int j = 0; j < MAX_TEAMS_ID_RTS; j++ )
		{
			if( g_RTSR->GetType( j ) == GRTYPE_CPU && g_RTSR->GetPosition(j)  == position )
			{
				char szbuf[144];	// more than 128
				Q_snprintf( szbuf, sizeof(szbuf), "gr_requestposition -1 %d", j );

				engine->ClientCmd( szbuf );		
				break;
			}
		}
	}
	else if( pPlayer == g_RTSR->GetGameMaster() )
	{
		//Msg("Player is gamemaster, his slot is %d and his position is %d\n", pPlayer->GetSlot(), g_RTSR->GetPosition(pPlayer->GetSlot() ) );
		if( g_RTSR->GetPosition(pPlayer->GetSlot() ) == -1 )
		{
			char szbuf[144];	// more than 128
			Q_snprintf( szbuf, sizeof(szbuf), "gr_requestposition %d %d", position, pPlayer->GetSlot() );

			engine->ClientCmd( szbuf );	
		}
		else
		{
			for( int j = 0; j < MAX_TEAMS_ID_RTS; j++ )
			{
				if( g_RTSR->GetType( j ) == GRTYPE_CPU && g_RTSR->GetPosition(j)  == -1 )
				{
					char szbuf[144];	// more than 128
					Q_snprintf( szbuf, sizeof(szbuf), "gr_requestposition %d %d", position, j );

					engine->ClientCmd( szbuf );		
					break;
				}
			}			
		}
	}
	else 
	{
		char szbuf[144];	// more than 128
		Q_snprintf( szbuf, sizeof(szbuf), "gr_requestposition %d %d", position, pPlayer->GetSlot() );

		engine->ClientCmd( szbuf );	
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::OnCommand(const char *command) 
{ 
	if (!stricmp(command, "bposition_0")) 
	{ 
		ActionPosition(0);	
	} 
	else if (!stricmp(command, "bposition_1")) 
	{ 
		ActionPosition(1);		
	} 
	else if (!stricmp(command, "bposition_2")) 
	{ 
		ActionPosition(2);			
	} 
	else if (!stricmp(command, "bposition_3")) 
	{ 
		ActionPosition(3);		
	} 
	else if (!stricmp(command, "bposition_4")) 
	{ 
		ActionPosition(4);			
	} 
	else if (!stricmp(command, "bposition_5")) 
	{ 
		ActionPosition(5);		
	} 
	else if (!stricmp(command, "bposition_6")) 
	{ 
		ActionPosition(6);			
	} 
	else if (!stricmp(command, "bposition_7")) 
	{ 
		ActionPosition(7);			
	} 
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::OnThink()
{
	int itemid = pMapList->GetSelectedItem( 0 );
	if( itemid != -1 )
	{
		KeyValues *selected = pMapList->GetItem( itemid );
		if( selected != m_pSelected )
		{
			m_pSelected = selected;
			//pMapInfo->SetText( m_pSelected->GetString( "map_description", "No description available!") );

			char szbuf[144];	// more than 128
			Q_snprintf( szbuf, sizeof(szbuf), "gr_requestmap %s", m_pSelected->GetString("name") );

			engine->ClientCmd( szbuf );
		}
	}
	else
	{
		m_pSelected = NULL;
	}

	if( !g_RTSR )
		return;

	// get local player to compare with the owner
	C_HL2Wars_Player* pPlayer = C_HL2Wars_Player::GetLocalHL2WarsPlayer();
	if( !pPlayer )
		return;	

	// Update positions buttons ( maybe make it some cleaner? )
	color32 color;
	color.r = color.g = color.b = color.a = 1.0f;
	for( int i = 0; i < MAX_TEAMS_ID_RTS; i++ )
	{
		// Position is not available, so don't care 
		if( !m_bPositionsAvailable[i] )
			continue;

		// we can always click a free position
		if( g_RTSR->IsPositionFree(i)  )
		{
			m_pPositions[i]->SetEnabled(true);
			m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_ENABLED, &m_pImagesPositions[8], color);
			m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_ENABLED_MOUSE_OVER, &m_pImagesPositions[8], color);
			m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_PRESSED, &m_pImagesPositions[8], color);	
		}
		// we can always click or own position to give the position free
		else if( g_RTSR->GetPosition( pPlayer->GetSlot() )  == i )
		{
			m_pPositions[i]->SetEnabled(true);
			m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_ENABLED, &m_pImagesPositions[pPlayer->GetSlot()], color);
			m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_ENABLED_MOUSE_OVER, &m_pImagesPositions[pPlayer->GetSlot()], color);
			m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_PRESSED, &m_pImagesPositions[pPlayer->GetSlot()], color);
		}
		// if we are the gamemaster, we can do a few things more
		else if( pPlayer == g_RTSR->GetGameMaster() )
		{
			for( int j = 0; j < MAX_TEAMS_ID_RTS; j++ )
			{
				if( g_RTSR->GetType( j ) == GRTYPE_CPU && g_RTSR->GetPosition(j)  == i )
				{
					m_pPositions[i]->SetEnabled(true);
					m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_ENABLED, &m_pImagesPositions[j], color);
					m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_ENABLED_MOUSE_OVER, &m_pImagesPositions[j], color);
					m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_PRESSED, &m_pImagesPositions[j], color);	
					return;
				}
			}

			// not a cpu, so it must be a player
			if( g_RTSR->GetIndex( i ) < 1 || g_RTSR->GetIndex( i ) > gpGlobals->maxClients )
				continue;

			C_HL2Wars_Player *pPlayerSlot = ToHL2WarsPlayer(UTIL_PlayerByIndex( g_RTSR->GetIndex( i ) ));
			if(!pPlayerSlot)
				continue;

			m_pPositions[i]->SetEnabled(false);
			m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_DISABLED, &m_pImagesPositions[pPlayerSlot->GetSlot()], color);
		}
		// in the last case, just show who is occupying this slot and make it not clickable
		else
		{
			// check for cpu's
			for( int j = 0; j < MAX_TEAMS_ID_RTS; j++ )
			{
				if( g_RTSR->GetType( j ) == GRTYPE_CPU && g_RTSR->GetPosition(j)  == i )
				{
					m_pPositions[i]->SetEnabled(false);
					m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_DISABLED, &m_pImagesPositions[j], color);
					return;
				}
			}

			// no cpu, so it must be a player
			if( g_RTSR->GetIndex( i ) < 1 || g_RTSR->GetIndex( i ) > gpGlobals->maxClients )
				continue;

			C_HL2Wars_Player *pPlayerSlot = ToHL2WarsPlayer(UTIL_PlayerByIndex( g_RTSR->GetIndex( i ) ));
			if(!pPlayerSlot)
				continue;

			m_pPositions[i]->SetEnabled(false);
			m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_DISABLED, &m_pImagesPositions[pPlayerSlot->GetSlot()], color);
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::Paint()
{
	BaseClass::Paint();

	if ( m_nMapTextureID < 0 )
		return;
	
	Vertex_t points[4] =
	{
		//upper left 0,0
		Vertex_t( Vector2D((GetWide()*0.3),0), Vector2D(0,0) ),

		//UPPER RIGHT 1023, 0
		Vertex_t( Vector2D((GetWide()*0.3)+(GetTall()*0.75),0), Vector2D(1,0) ),

		//LOWER LEFT 1023, 1
		Vertex_t( Vector2D((GetWide()*0.3)+(GetTall()*0.75),(GetTall()*0.75)), Vector2D(1,1) ),

		Vertex_t( Vector2D((GetWide()*0.3),(GetTall()*0.75)), Vector2D(0,1) )
	};

	int alpha = 255.0f * .8; clamp( alpha, 1, 255 );
	
	surface()->DrawSetColor( 255,255,255, alpha );
	surface()->DrawSetTexture( m_nMapTextureID );
	surface()->DrawTexturedPolygon( 4, points );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::Reset()
{
	pMapList->DeleteAllItems();
}

//-----------------------------------------------------------------------------
// Purpose: NOT IN USE: Server sends map list.
//-----------------------------------------------------------------------------
void CMapSelector::RefreshMapsList( void )
{
	FileFindHandle_t findHandle;
	const char *pFilename = filesystem->FindFirstEx( "maps/wmp_*.bsp", "GAME", &findHandle );
	while ( pFilename != NULL )
	{
		char *mapname;
		mapname = (char *)malloc( (strlen( pFilename ) - 3) * sizeof( char ) );
		Q_strncpy(&mapname[0], pFilename, strlen( pFilename ) - 3);
		mapname[ strlen( pFilename ) - 4 ] = '\0';
		
		KeyValues *pData = new KeyValues( "data" );
		pData->SetString( "name", mapname );

		pMapList->AddItem( pData, 0, false, true );

		pData->deleteThis();

		pFilename = filesystem->FindNext( findHandle );
	}
	filesystem->FindClose( findHandle );	
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::AddMapToList( char *map )
{
	KeyValues *pData = new KeyValues( "data" );
	pData->SetString( "name", map );

	pMapList->AddItem( pData, 0, false, true );

	pData->deleteThis();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::SetMapName(char *mapname )
{
	char szbuf[144];	// more than 128
	Q_snprintf( szbuf, sizeof(szbuf), "Name: %s", mapname );

	m_pMapName->SetText(szbuf);

	// load the overview txt file
	KeyValues *mapKeyValues = new KeyValues( mapname );

	char tempfile[MAX_PATH];
	Q_snprintf( tempfile, sizeof( tempfile ), "resource/maps/%s.txt", mapname );
	
	if ( !mapKeyValues->LoadFromFile( filesystem, tempfile, "GAME" ) )
	{
		DevMsg( 1, "Error! CMapSelector::SetMapName: couldn't load file %s.\n", tempfile );
		m_nMapTextureID = -1;
		return;
	}

	m_MapOrigin.x	= mapKeyValues->GetInt("pos_x");
	m_MapOrigin.y	= mapKeyValues->GetInt("pos_y");
	m_fMapScale     = mapKeyValues->GetFloat("scale",1.0f);

	//Q_snprintf( szbuf, sizeof(szbuf), "overviews/%s", m_pSelected->GetString("name") );
	// set the map texture
	m_nMapTextureID = surface()->CreateNewTextureID();
	surface()->DrawSetTextureFile( m_nMapTextureID, mapKeyValues->GetString("material"), true, false);

	// now, set the start positions
	for( int i = 0; i < MAX_TEAMS_ID_RTS; i++ )
	{
		if( m_bPositionsAvailable[i] )
		{
			Vector2D pos2D = MapToPanel( WorldToMap( m_vPositionsOrigin[i] ) );	
			m_pPositions[i]->SetPos( (GetWide()*0.3)+pos2D.x, pos2D.y );
			m_pPositions[i]->SetVisible(true);
		}
		else
		{
			m_pPositions[i]->SetVisible(false);
		}
	}	
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::SetPositionOrigin(int i, Vector position )
{
	m_vPositionsOrigin[i] = position;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::SetPosAvailable(int i, bool state )
{
	m_bPositionsAvailable[i] = state;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
Vector2D CMapSelector::WorldToMap( const Vector &worldpos )
{
	Vector2D offset( worldpos.x - m_MapOrigin.x, worldpos.y - m_MapOrigin.y);

	offset.x /=  m_fMapScale;
	offset.y /= -m_fMapScale;

	return offset;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
Vector2D CMapSelector::MapToPanel( const Vector2D &mappos )
{
	int pwidth, pheight; 
	Vector2D panelpos;

	pwidth = (GetTall()*0.75);
	pheight = (GetTall()*0.75);

	Vector offset;
	offset.x = mappos.x - m_MapCenter.x;
	offset.y = mappos.y - m_MapCenter.y;
	offset.z = 0;

	// find the actual zoom from the animationvar m_fZoom and the map zoom scale
	float fScale = 1.0 / 1024.0;

	offset.x *= fScale;
	offset.y *= fScale;

	panelpos.x = (pwidth * 0.5f) + (pheight * offset.x);
	panelpos.y = (pheight * 0.5f) + (pheight * offset.y);

	return panelpos;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::SetMapPlayers(char *players )
{
	char szbuf[144];	// more than 128
	Q_snprintf( szbuf, sizeof(szbuf), "Players: %s", players );

	m_pPlayers->SetText(szbuf);
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMapSelector::ApplySchemeSettings( IScheme *pScheme )
{
	BaseClass::ApplySchemeSettings( pScheme );

	// map list
	pMapList->SetFont( pScheme->GetFont( "DefaultSmall" ) );
	pMapList->SetFgColor( LIST_TEXT_COLOR );	
	pMapList->SetSize( 0.3 * GetWide(), GetTall() );

	// labels
	m_pMapName->SetFont( pScheme->GetFont( "DefaultSmall" ) );
	m_pMapName->SetFgColor( LIST_TEXT_COLOR );	
	m_pMapName->SetSize( 0.7 * GetWide(), 0.05 * GetTall() );
	m_pMapName->SetPos( (GetWide()*0.3), (GetTall()*0.75) );

	m_pPlayers->SetFont( pScheme->GetFont( "DefaultSmall" ) );
	m_pPlayers->SetFgColor( LIST_TEXT_COLOR );	
	m_pPlayers->SetSize( 0.7 * GetWide(), 0.05 * GetTall() );
	m_pPlayers->SetPos( (GetWide()*0.3), (GetTall()*0.82) );

	color32 color;
	color.r = color.g = color.b = color.a = 1.0f;
	// create position buttons
	for( int i = 0; i < MAX_TEAMS_ID_RTS; i++ )
	{
		m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_ENABLED, &m_pImagesPositions[8], color);
		m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_ENABLED_MOUSE_OVER, &m_pImagesPositions[8], color);
		m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_PRESSED, &m_pImagesPositions[8], color);
		m_pPositions[i]->SetImage( CBitmapButtonRTS::BUTTON_DISABLED, &m_pImagesPositions[8], color);
		m_pPositions[i]->SetPaintBackgroundEnabled( false );
		m_pPositions[i]->SetPaintBorderEnabled( false );
		m_pPositions[i]->SetSize(vgui::scheme()->GetProportionalScaledValueEx( GetScheme(), 16 ),
			vgui::scheme()->GetProportionalScaledValueEx( GetScheme(), 16 ));
	}
}


//-----------------------------------------------------------------------------
// Purpose: Player list stuff follows here
//-----------------------------------------------------------------------------
CPlayerListEntry::CPlayerListEntry( vgui::Panel *parent, int slot  ) : BaseClass( parent, "playerentry" )
{
	vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFile("resource/GameLobbyScheme.res", "GameLobbyScheme");
	SetScheme( scheme );

	m_iSlot = slot;
	m_pOwner = NULL;

	//	set up the label for the name of the owner
	m_pSlotName = new ComboBox(this, "slot", 3 , false);
	m_pSlotName->SetScheme(vgui::scheme()->LoadSchemeFromFile("resource/SourceScheme.res", "SourceScheme"));	
	m_pSlotName->SetVisible( true );
	m_pSlotName->AddActionSignalTarget( this );
	m_pSlotName->SetEnabled( false );

	KeyValues *pData = new KeyValues( "UserData", "slot_option", GROPEN_SLOT );
	m_pSlotName->AddItem( "Open slot", pData );
	pData->deleteThis();

	pData = new KeyValues( "UserData", "slot_option", GROCCUPY_SLOT );
	m_pSlotName->AddItem( "Occupy slot", pData );
	pData->deleteThis();

	pData = new KeyValues( "UserData", "slot_option", GRCPUOCCUPY_SLOT );
	m_pSlotName->AddItem( "Add CPU", pData );
	pData->deleteThis();

	// set up the color picker
	m_pColor = new ComboBox(this, "color", 10 , false);
	m_pColor->SetScheme(vgui::scheme()->LoadSchemeFromFile("resource/SourceScheme.res", "SourceScheme"));	
	m_pColor->SetVisible( true );	
	m_pColor->AddActionSignalTarget( this );
	m_pColor->SetEnabled( false );

	// Setup color combo box
	pData = new KeyValues( "UserData", "selected_color", 1 );
	m_pColor->AddItem( "Orange", pData );
	pData->deleteThis();

	pData = new KeyValues( "UserData", "selected_color", 2 );
	m_pColor->AddItem( "Blue", pData );
	pData->deleteThis();

	pData = new KeyValues( "UserData", "selected_color", 3 );
	m_pColor->AddItem( "Cyan", pData );
	pData->deleteThis();

	pData = new KeyValues( "UserData", "selected_color", 4 );
	m_pColor->AddItem( "Green", pData );
	pData->deleteThis();

	pData = new KeyValues( "UserData", "selected_color", 5 );
	m_pColor->AddItem( "Red", pData );
	pData->deleteThis();	

	// setup faction combo box
	m_pFaction = new ComboBox(this, "color", 10 , false);
	m_pFaction->SetScheme(vgui::scheme()->LoadSchemeFromFile("resource/SourceScheme.res", "SourceScheme"));	
	m_pFaction->SetVisible( true );	
	m_pFaction->AddActionSignalTarget( this );
	m_pFaction->SetEnabled( false );

	// Setup color combo box
	pData = new KeyValues( "UserData", "selected_faction", FACTION_REBEL );
	m_pFaction->AddItem( "Rebels", pData );
	pData->deleteThis();

	pData = new KeyValues( "UserData", "selected_faction", FACTION_COMBINE );
	m_pFaction->AddItem( "Combine", pData );
	pData->deleteThis();

	// ready button
	m_pReady = new CheckButton( this, "Ready", "" );
	m_pReady->SetEnabled( false );
	m_pReady->AddActionSignalTarget( this );
}

//-----------------------------------------------------------------------------
// Purpose: Handles changes to combo boxes
//-----------------------------------------------------------------------------
void CPlayerListEntry::OnTextChanged( KeyValues *pData )
{
	Panel *panel = reinterpret_cast<vgui::Panel *>( pData->GetPtr("panel") );

	vgui::ComboBox *box = dynamic_cast<vgui::ComboBox *>( panel );

	if ( box == m_pColor )
	{
		C_HL2Wars_Player *pPlayer = C_HL2Wars_Player::GetLocalHL2WarsPlayer();
		if( m_iSlot != pPlayer->GetSlot() && pPlayer != g_RTSR->GetGameMaster() && g_RTSR->GetType(m_iSlot) != GRTYPE_CPU )
			return;

		KeyValues *kv = m_pColor->GetActiveItemUserData();
		if( kv )
		{
			char szbuf[144];	// more than 128
			Q_snprintf( szbuf, sizeof(szbuf), "gr_requestcolor %d %d", kv->GetInt( "selected_color" ), m_iSlot );

			engine->ClientCmd( szbuf );
		}
	}
	else if( box == m_pFaction )
	{
		C_HL2Wars_Player *pPlayer = C_HL2Wars_Player::GetLocalHL2WarsPlayer();
		if( m_iSlot != pPlayer->GetSlot() && pPlayer != g_RTSR->GetGameMaster() && g_RTSR->GetType(m_iSlot) != GRTYPE_CPU  )
			return;

		KeyValues *kv = m_pFaction->GetActiveItemUserData();
		if( kv )
		{
			char szbuf[144];	// more than 128
			Q_snprintf( szbuf, sizeof(szbuf), "gr_requestfaction %d %d", kv->GetInt( "selected_faction" ), m_iSlot  );

			engine->ClientCmd( szbuf );
		}
	}
	else if( box == m_pSlotName )
	{
		KeyValues *kv = m_pSlotName->GetActiveItemUserData();
		if( kv )
		{
			char szbuf[144];	// more than 128
			Q_snprintf( szbuf, sizeof(szbuf), "gr_slotaction %d %d", kv->GetInt( "slot_option" ), m_iSlot );

			engine->ClientCmd( szbuf );
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: Handles changes in check buttons
//-----------------------------------------------------------------------------
void CPlayerListEntry::OnCheckButtonChecked( vgui::Panel *panel )
{
	vgui::CheckButton *pCB = dynamic_cast<vgui::CheckButton *>( panel );

	if( pCB == m_pReady )
	{
		char szbuf[144];	// more than 128
		Q_snprintf( szbuf, sizeof(szbuf), "gr_ready %d", m_pReady->IsSelected() );

		engine->ClientCmd( szbuf );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPlayerListEntry::UpdateGRInfo( int index, int slot )
{
	// update owner of this slot
	m_pOwner = UTIL_PlayerByIndex( index );

	// get local player to compare with the owner
	C_BasePlayer* pPlayer = C_BasePlayer::GetLocalPlayer();
	if( !pPlayer )
		return;	

	// update slot options
	if( m_pOwner )
	{
		m_pSlotName->SetEnabled( false );
	}

	// update free colors in combo box
	for( int i = 0; i < TOTAL_COLORS; i++ )
	{
		if( g_RTSR->IsColorFree(i) )
		{
			m_pColor->SetItemEnabled( UTIL_GetColorName(i), true );
		}
		else
		{
			m_pColor->SetItemEnabled( UTIL_GetColorName(i), false );
		}
	}

	m_pColor->SetText( UTIL_GetColorName( g_RTSR->GetGRColor( slot ) ) );	// update color
	m_pFaction->SetText( UTIL_GetFactionName( g_RTSR->GetFaction( slot ) ) );
	SetSlotName( g_PR->GetPlayerName(index) );	// set name

	// update ready button
	if( pPlayer != m_pOwner )
	{
		m_pReady->SetSelected( g_RTSR->IsReady( slot ) );
	}

	// set options editable if ours
	if( pPlayer == m_pOwner )
	{
		m_pColor->SetEnabled( true );
		m_pFaction->SetEnabled( true );
		m_pReady->SetEnabled( true );
		m_pReady->AddActionSignalTarget( this );
	}
	else
	{
		m_pColor->SetEnabled( false );
		m_pFaction->SetEnabled( false );
		m_pReady->SetEnabled( false );
		m_pReady->RemoveActionSignalTarget( this );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPlayerListEntry::UpdateGRInfoCPU( int slot )
{
	// The owner of this slot is the gamemaster
	m_pOwner = g_RTSR->GetGameMaster();

	// get local player to compare with the owner
	C_BasePlayer* pPlayer = C_BasePlayer::GetLocalPlayer();
	if( !pPlayer )
		return;	

	// update slot options
	if( m_pOwner == pPlayer )
	{
		m_pSlotName->SetItemEnabled( GROCCUPY_SLOT, false );
		m_pSlotName->SetEnabled( true );
	}
	else
	{
		m_pSlotName->SetItemEnabled( GROCCUPY_SLOT, true );
		m_pSlotName->SetEnabled( false );
	}

	// update free colors in combo box
	for( int i = 0; i < TOTAL_COLORS; i++ )
	{
		if( g_RTSR->IsColorFree(i) )
		{
			m_pColor->SetItemEnabled( UTIL_GetColorName(i), true );
		}
		else
		{
			m_pColor->SetItemEnabled( UTIL_GetColorName(i), false );
		}
	}

	m_pColor->SetText( UTIL_GetColorName( g_RTSR->GetGRColor( slot ) ) );	// update color
	m_pFaction->SetText( UTIL_GetFactionName( g_RTSR->GetFaction( slot ) ) );
	SetSlotName( "CPU" );	// set name

	m_pReady->SetSelected( true );

	// set options editable if ours
	if( pPlayer == m_pOwner )
	{
		m_pColor->SetEnabled( true );
		m_pFaction->SetEnabled( true );
		m_pReady->SetEnabled( false );
		m_pReady->RemoveActionSignalTarget( this );
	}
	else
	{
		m_pColor->SetEnabled( false );
		m_pFaction->SetEnabled( false );
		m_pReady->SetEnabled( false );
		m_pReady->RemoveActionSignalTarget( this );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPlayerListEntry::Clear()
{
	m_pOwner = NULL;
	SetSlotName( "		" );
	m_pSlotName->SetItemEnabled( GROCCUPY_SLOT, true );
	m_pSlotName->SetEnabled( true );
	m_pColor->SetEnabled( false );
	m_pFaction->SetEnabled( false );
	//m_pPosition->SetEnabled( false );
	m_pReady->SetEnabled( false );
	m_pReady->RemoveActionSignalTarget( this );
	m_pReady->SetSelected(false);
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPlayerListEntry::SetSlotName( const char *name )
{
	m_pSlotName->SetText( name );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPlayerListEntry::ApplySchemeSettings( IScheme *pScheme )
{
	BaseClass::ApplySchemeSettings( pScheme );

	SetBgColor( Color( 20, 20, 20, 128 ) );

	vgui::HFont hFont = pScheme->GetFont( "Trebuchet18" );
	m_pSlotName->SetFont( hFont );
	m_pSlotName->SetSize( 100, 25);
	m_pSlotName->SetPos( 0, 0 );
	m_pSlotName->GetMenu()->MakeReadyForUse();
	m_pSlotName->GetMenu()->SetBgColor( BLACK_BAR_COLOR );

	m_pColor->SetFont( hFont );
	m_pColor->SetSize( 100, 25);
	m_pColor->SetPos( 100, 0 );
	m_pColor->GetMenu()->MakeReadyForUse();
	m_pColor->GetMenu()->SetBgColor( BLACK_BAR_COLOR );

	m_pFaction->SetFont( hFont );
	m_pFaction->SetSize( 100, 25);
	m_pFaction->SetPos( 200, 0 );
	m_pFaction->GetMenu()->MakeReadyForUse();
	m_pFaction->GetMenu()->SetBgColor( BLACK_BAR_COLOR );

	m_pReady->SetFont( hFont );
	m_pReady->SetSize( 50, 25);
	m_pReady->SetPos( 300, 0);
}

//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CPlayerList::CPlayerList( vgui::Panel *parent ) : BaseClass( parent, "playerlist" )
{
	m_pGRW = (CGameRoomWindow *)parent;
	for ( int i = 0; i < MAX_TEAMS_ID_RTS; i++ )
		m_pPlayerList[i] = new CPlayerListEntry( this, i );

	vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFile("resource/GameLobbyScheme.res", "GameLobbyScheme");
	SetScheme( scheme );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPlayerList::ApplySchemeSettings( IScheme *pScheme )
{
	BaseClass::ApplySchemeSettings( pScheme );

	int y = 0;
	for ( int i = 0; i < MAX_TEAMS_ID_RTS; i++ )
	{
		m_pPlayerList[i]->SetPos( 0, y );
		m_pPlayerList[i]->SetSize( 400, 25 );
		y += 25;
	}
}

//-----------------------------------------------------------------------------
// Purpose: OnThink
//-----------------------------------------------------------------------------
void CPlayerList::OnThink()
{
	if( !g_RTSR || !g_RTSR )
		return;

	// check gamemaster permissions
	if( C_BasePlayer::GetLocalPlayer() == g_RTSR->GetGameMaster() )
	{
		m_pGRW->GetMapSelector()->SetEnabled( true );
		m_pGRW->GetLaunchButton()->SetEnabled( true );
	}
	else
	{
		m_pGRW->GetMapSelector()->SetEnabled( false );
		m_pGRW->GetLaunchButton()->SetEnabled( false );
	}

	// update list
	for ( int i = 0; i < MAX_TEAMS_ID_RTS; i++ )
	{
		if( g_RTSR->GetIndex( i ) > 0 && g_RTSR->GetIndex( i ) <= gpGlobals->maxClients )
		{
			m_pPlayerList[i]->UpdateGRInfo( g_RTSR->GetIndex( i ), i );
		}
		else if( g_RTSR->GetType(i) == GRTYPE_CPU )
		{
			m_pPlayerList[i]->UpdateGRInfoCPU( i );
		}
		else 
		{
			m_pPlayerList[i]->Clear();
		}
	}
}





