#pragma semicolon 1
#include <sourcemod>
#include <sdktools>
#include <sdktools_functions>
#include <adminmenu>

#define PLUGIN_VERSION "1.3"

new bool:bL8DEnabled;

public Plugin:myinfo = 
{
	name = "Left8Dead",
	author = "Mad_Dugan",
	description = "Allows 8 players to play as survivor",
	version = PLUGIN_VERSION,
	url = "http://forums.alliedmods.net/showthread.php?t=89422"
};

public OnPluginStart()
{
	decl String:ModName[50];
	GetGameFolderName(ModName, sizeof(ModName));

	if(!StrEqual(ModName, "left4dead", false))
	{
		SetFailState("Use this in Left 4 Dead only.");
	}

	CreateConVar("sm_l8d_version", PLUGIN_VERSION, "本插件版本", FCVAR_PLUGIN|FCVAR_SPONLY|FCVAR_REPLICATED|FCVAR_NOTIFY);
	
	RegAdminCmd("sm_l8d_enable", L8DEnable, ADMFLAG_KICK, "允許L8D");
	RegAdminCmd("sm_l8d_changemap", L8DMapMenu, ADMFLAG_KICK, "為L8D轉換地圖");
	
	HookEvent("finale_vehicle_leaving", Event_FinaleVehicleLeaving);
	
	bL8DEnabled = false;
}

public OnEventShutdown()
{
	UnhookEvent("finale_vehicle_leaving", Event_FinaleVehicleLeaving);
}

public OnMapStart()
{
	if(bL8DEnabled)
	{
		new String:MapName[80];
		GetCurrentMap(MapName, sizeof(MapName));
		
		if (StrContains(MapName, "_vs_", false) != -1)
		{
			SetConVarInt(FindConVar("z_difficulty_locked"), 0);
			SetConVarString(FindConVar("z_difficulty"), "Impossible");			
		}
		else
		{
			// only do this for first map
			if (StrContains(MapName, "01_", false) != -1)
			{
				CreateTimer(5.0, CreateBots);
			}
			
			// set stats to be expert mode like
			SetConVarInt(FindConVar("z_difficulty_locked"), 0);
			SetConVarString(FindConVar("z_difficulty"), "Impossible");
			SetConVarInt(FindConVar("director_must_create_all_scavenge_items"), 1);
		}
	}
}

public OnClientDisconnect(client)
{
	// TODO: handle bot removal
}

public Event_FinaleVehicleLeaving(Handle:event, const String:name[], bool:dontBroadcast)
{
	// TODO: Teleport non-incapped extra players to same place as primary players
	// so they don't fall through rescue vehicle
}

public Action:L8DEnable(client, args) 
{
	new String:MapName[80];
	GetCurrentMap(MapName, sizeof(MapName));
	
	if (StrContains(MapName, "_vs_", false) != -1)
	{
		bL8DEnabled = true;
		
		UnsetCheatVar(FindConVar("director_no_human_zombies"));
		UnsetCheatVar(FindConVar("sb_all_bot_team"));
		UnsetCheatVar(FindConVar("director_must_create_all_scavenge_items"));
		
		SetConVarInt(FindConVar("sv_alltalk"), 1); // so you can tell the infected what is happening
		SetConVarInt(FindConVar("vs_max_team_switches"), 9999);
		SetConVarInt(FindConVar("sb_all_bot_team"), 1);
		SetConVarInt(FindConVar("director_no_human_zombies"), 1);
		SetConVarInt(FindConVar("director_must_create_all_scavenge_items"), 1);
		
		PrintToChatAll("\x01[SM] Left8Dead is now enabled.  Admin can now select a co-op map\x03");
		
		L8DMapMenu(client, args);
	}
	else
	{
		// Can only enable during an initial vs map
		PrintToChatAll("\x01[SM] Left 8 Dead只可以在對抗模式中啟動.\x03");
		// bL8DEnabled = false;
	}
}

public Action:L8DMapMenu(client, args) 
{
	if(bL8DEnabled)
	{
		new Handle:menu = CreateMenu(L8DMapMenuHandler);
	
		SetMenuTitle(menu, "L8D co-op map choice");
		AddMenuItem(menu, "option1", "毫不留情");
		AddMenuItem(menu, "option2", "死亡機場");
		AddMenuItem(menu, "option3", "死亡喪鐘");
		AddMenuItem(menu, "option4", "嗜血豐收");
		AddMenuItem(menu, "option5", "隨機");
		AddMenuItem(menu, "option6", "舉行投票");
		SetMenuExitButton(menu, true);
	
		DisplayMenu(menu, client, MENU_TIME_FOREVER);
    }
	
	return Plugin_Handled;
}

public Action:L8DMapMenuVote(client, args)
{
	new Handle:menu = CreateMenu(L8DMapMenuVoteHandler);
	
	SetMenuTitle(menu, "L8D合作地圖選擇");
	AddMenuItem(menu, "option1", "毫不留情");
	AddMenuItem(menu, "option2", "死亡機場");
	AddMenuItem(menu, "option3", "死亡喪鐘");
	AddMenuItem(menu, "option4", "嗜血豐收");
	AddMenuItem(menu, "option5", "隨機");
	SetMenuExitButton(menu, false);
	
	VoteMenuToAll(menu, 20);
	
	return Plugin_Handled;
}

public L8DMapMenuHandler(Handle:menu, MenuAction:action, client, itemNum)
{
    if ( action == MenuAction_Select ) 
	{
        switch (itemNum)
        {
            case 0: //No Mercy
            {
				ServerCommand("changelevel l4d_hospital01_apartment");
            }
            case 1: //Dead Air
            {
				ServerCommand("changelevel l4d_airport01_greenhouse");
            }
            case 2: //Death Toll
            {
				ServerCommand("changelevel l4d_smalltown01_caves");
            }
			case 3: //Blood Harvest
            {
				ServerCommand("changelevel l4d_farm01_hilltop");
            }
			case 4: // Random
			{
				// pick random and call this function again
				new rnditemNum = GetRandomInt(0, 3);
				L8DMapMenuHandler(menu, MenuAction_Select, client, rnditemNum);
			}			
			case 5: // Vote
			{
				L8DMapMenuVote(client, 0);
			}
        }
    }
}

public L8DMapMenuVoteHandler(Handle:menu, MenuAction:action, param1, param2)
{
	if (action == MenuAction_End)
	{
		CloseHandle(menu);
	} 
	else if (action == MenuAction_VoteEnd) 
	{
		L8DMapMenuHandler(menu, MenuAction_Select, 0, param1);
	}
}

public Action:CreateBots(Handle:timer)
{
/*
	// create a bot for each spectator
	for(new i=1; i <= MaxClients; i++)
	{
		if(IsClientConnected(i) && IsClientInGame(i))
		{
			if(GetClientTeam(i) == 1)
			{
				l4dbot();
			}
		}		
	}	
*/
	for(new i=0;i<4;i++)
	{
		l4dbot();
	}
	
	CreateTimer(20.0, SwitchSpectators);
	PrintToChatAll("\x01[SM] 觀戰方會自動轉移到倖存者方.\x03");
}

public Action:KickBots()
{
	// housecleaning
	for(new i=1; i <= MaxClients; i++)
	{
		if(IsClientConnected(i) && IsClientInGame(i))
		{
			// only kick survivor bots
			if(GetClientTeam(i) == 2)
			{
				
			}
		}		
	}
}

public Action:SwitchSpectators(Handle:timer)
{
	// switch the spectators
	for(new i=1; i <= MaxClients; i++)
	{
		if(IsClientConnected(i) && IsClientInGame(i))
		{
			if(GetClientTeam(i) == 1)
			{
				FakeClientCommand(i, "jointeam 2");
			}
		}		
	}
	
	PrintToChatAll("\x01[SM] 如有有任何觀戰者未轉變隊伍, 應立即按'~'在Console中輸入'jointeam 2'.\x03");
}

UnsetCheatVar(Handle:hndl)
{
	new flags = GetConVarFlags(hndl);
	flags &= ~FCVAR_CHEAT;
	SetConVarFlags(hndl, flags);
}

SetCheatVar(Handle:hndl)
{
	new flags = GetConVarFlags(hndl);
	flags |= FCVAR_CHEAT;
	SetConVarFlags(hndl, flags);
}

// lifted from l4dhax
public Action:l4dbot()
{
	new bot = CreateFakeClient("我不是真的.");
	ChangeClientTeam(bot,2);
	DispatchKeyValue(bot,"classname","電腦倖存者");
	DispatchSpawn(bot);
	CreateTimer(5.0,kickbot,bot); // reduced timer
}

public Action:kickbot(Handle:timer, any:value)
{
	KickClient(value,"fake player");
	return Plugin_Stop;
}