/*
For Counter Strike Source

Description: Hidders can change owne model.

Todo:
-remove bomb
-night effect

*/
//CSS Handle
new Handle:hModelMenu;
new Handle:CVAR_AllowRadar;
new Handle:CVAR_HidersSpeed;
new Handle:CVAR_RandomChoose;
new Handle:BlockDuckTimer;

public EnableHookEvents()
{
	HookEvent("item_pickup", Event_ItemPickup);
	HookEvent("bullet_impact", Event_BulletImpact);
	HookEvent("weapon_fire", Event_WeaponFire);
	HookEvent("player_hurt", Event_PlayerHurt);
	HookEvent("hostage_follows", Event_HostageRescued);
	
	BlockDuckTimer = CreateTimer(1.0, Timer_BlockDuck, 0, TIMER_REPEAT);
}

public DisableHookEvents()
{
	UnhookEvent("item_pickup", Event_ItemPickup);
	UnhookEvent("bullet_impact", Event_BulletImpact);
	UnhookEvent("weapon_fire", Event_WeaponFire);
	UnhookEvent("player_hurt", Event_PlayerHurt);
	UnhookEvent("hostage_follows", Event_HostageRescued);
	
	KillTimer(BlockDuckTimer);
	BlockDuckTimer = INVALID_HANDLE;
}

public GamePluginStart()
{
	// Reenable ModelMenu
	RegConsoleCmd("hidemenu", HideItemMenu);	

	CVAR_AllowRadar = CreateConVar("sm_allowradar", "0", "0 = change CT-player to Spectator if cl_radaralpha > 0",FCVAR_PLUGIN|FCVAR_NOTIFY);
	CVAR_HidersSpeed = CreateConVar("sm_hidespeed", "1.2", "Change speed for Hiders",FCVAR_PLUGIN);
	CVAR_RandomChoose = CreateConVar("sm_randomchoose", "0", "Hiders get a random Model (no menue)",FCVAR_PLUGIN);
	
	SetRandomSeed(GetTime());
}

public GameMapStart()
{
	if(GetConVarInt(CVAR_PluginEnabled))
	{
		new String:Mapstr[256];
		GetCurrentMap(Mapstr, gMaxLength);
		LoadMapModels(Mapstr);
		
		//EnableThirdperson();
	}
}

public GameRoundStart()
{
	// Don't show playerinfo
	new Handle:hndlplayerid = FindConVar("mp_playerid");
	SetConVarInt(hndlplayerid, 1);
	
	// Freeze all Players
	StartFreezeTimer(GetConVarInt(CVAR_FreezeTime));
}

public Action:Timer_BlockDuck(Handle:timer, any:data)
{
	new client;

	for(new i=0;i<MAXPLAYERS;i++)
	{
		client = GetClientOfUserId(i);
		if(client > 0 && IsClientInGame(client))
		{
			if(GetClientTeam(client) == TEAM_1)
			{
				if(GetEntityFlags(client) & FL_DUCKING)
				{
					SetEntityFlags(client,FL_DUCKING,0);
				}
				
			}
		}
	}
		
	return Plugin_Handled;
}

stock SetEntityFlags(entity,flag,onoff)
{
    new flags = GetEntProp(entity,Prop_Data,"m_fFlags");
    
    if((flags & flag) > 0)
        return onoff == 1 ? 2 : 1 + 0 * SetEntProp(entity,Prop_Data,"m_fFlags",flags - flag);
    
    else
        return onoff == 0 ? 2 : 1 + 0 * SetEntProp(entity,Prop_Data,"m_fFlags",flags + flag);
        
}

public Action:Event_PlayerSpawn(Handle:event, const String:name[], bool:dontBroadcast)
{
	new client = GetClientOfUserId(GetEventInt(event, "userid"));
	new client_team = GetClientTeam(client);
    	if(client_team == TEAM_SPECTATOR || client_team == TEAM_NONE)
        	return Plugin_Continue;
    
   	if(!IsPlayerAlive(client))
        	return Plugin_Continue;

	if(client_team == TEAM_1)
	{
		new SpeedOffset;
		SpeedOffset=FindSendPropOffs("CCSPlayer","m_flLaggedMovementValue");
		SetEntDataFloat(client,SpeedOffset,GetConVarFloat(CVAR_HidersSpeed),true);

		if(GetConVarInt(CVAR_RandomChoose))
		{
			RandomModelChoose(client);
		}
		else
		{
			HideItemMenu(client,0);
		}
		
		
		
	}
	else if(client_team == TEAM_2)
	{
		FreezeClient(client);
		
		if(!GetConVarInt(CVAR_AllowRadar))
		{
			
			QueryClientConVar(client, "cl_radaralpha", ConVarQueryFinished:ClientRadarCheck, client);
		}
		PrintToChat(client,"You are now Seeker, wait %i seconds to find hiders!",GetConVarInt(CVAR_FreezeTime));
	}

	return Plugin_Continue;
}

public ClientRadarCheck(QueryCookie:cookie, client, ConVarQueryResult:result, const String:cvarName[], const String:cvarValue[])
{
	
	if(StringToInt(cvarValue) > 0)
	{
		ChangeClientTeam(client,TEAM_SPECTATOR);
		UnfreezeClient(client);
		PrintToChat(client,"\x03[!!]Radar not allowed!!");
		PrintToChat(client,"\x03[!!]Set cl_radaralpha 0 in console!!!");
		PrintHintText(client,"Set cl_radaralpha 0 in console!!!");
		PrintCenterText(client,"Set cl_radaralpha 0 in console!!!");
	}
}

public Action:Event_ItemPickup(Handle:event, const String:name[], bool:dontBroadcast)
{
	new client = GetClientOfUserId(GetEventInt(event, "userid"));
	new client_team = GetClientTeam(client);
	
	if(client_team == TEAM_1)
	{
    		for(new i=0;i < 28;i++)
    		{
				RemoveWeaponFromSlot(client, i);
    		}
	}
}

public Action:Event_BulletImpact(Handle:event, const String:name[], bool:dontBroadcast)
{
	new client = GetClientOfUserId(GetEventInt(event, "userid"));
	
	new client_oldhp = GetEntProp(client, Prop_Send, "m_iHealth");
	if(client_oldhp > 1)
	{
		SetEntityHealth(client,client_oldhp-2)
	}
	else
	{
		SlapPlayer(client,2,false);	//Client die!
	}
	return Plugin_Handled;
}

public Action:Event_WeaponFire(Handle:event, const String:name[], bool:dontBroadcast)
{
	new client = GetClientOfUserId(GetEventInt(event, "userid"));
	new String:client_weapon[256];
	GetEventString(event,"weapon",client_weapon,gMaxLength);
	
	if(strcmp(client_weapon,"knife") == 0)
	{
		new client_oldhp = GetEntProp(client, Prop_Send, "m_iHealth");
		
		if(client_oldhp > 1)
		{
			SetEntityHealth(client,client_oldhp-2);
		}
		else
		{
			SlapPlayer(client,2,false);	//Player die!
		}
	}
}

public Action:Event_PlayerHurt(Handle:event, const String:name[], bool:dontBroadcast)
{
	new client = GetClientOfUserId(GetEventInt(event, "userid"));
	
	new attackclient_id = GetEventInt(event, "attacker");
	new attackclient = GetClientOfUserId(attackclient_id);

	new client_team = GetClientTeam(client);
	//PrintToConsole(attackclient,"Hurt Player %i",client);
	if(attackclient > 0 && IsClientInGame(attackclient))
	{
		if(IsPlayerAlive(attackclient) && client_team == TEAM_1)
		{
			new client_oldhp = GetEntProp(attackclient, Prop_Send, "m_iHealth");
			SetEntityHealth(attackclient,client_oldhp+GetEventInt(event, "health"))
			PrintToConsole(attackclient,"Add HP %i",GetEventInt(event, "health"));
		}
	}
}


public Action:Event_HostageRescued(Handle:event, const String:name[], bool:dontBroadcast)
{
	new hostage = GetEventInt(event, "hostage");
	//RemoveEdict(hostage);
	SetEntityMoveType(hostage, MOVETYPE_NONE);
	
}

public HideItemMenuHandler(Handle:menu, MenuAction:action, param1, param2)
{
	// param1: client
	// param2: menu position
	
	if (action == MenuAction_Select)
	{
		new client_team = GetClientTeam(param1);
		new String:info[256];
		new String:disp[256];
		new style = 0;
		
		
		if(client_team == TEAM_1)
		{	
			GetMenuItem(menu, param2, info, sizeof(info),style,disp, sizeof(disp));
			
			if(IsModelPrecached(info))
			{
				PrintToChat(param1,"You are a \"%s\".",disp);
				PrintToChat(param1,"Go and hide now!");
				SetEntityModel(param1, info);
			}
		}
	}

	else if (action == MenuAction_Cancel)
	{
		//PrintToServer("Client %d's menu was cancelled.  Reason: %d", param1, param2);
	}

	else if (action == MenuAction_End)
	{
		//CloseHandle(hModelMenu);
	}
}
 
public Action:HideItemMenu(client, args)
{	
	if(GetConVarInt(CVAR_RandomChoose) == 0)
	{
		DisplayMenu(hModelMenu, client, MENU_TIME_FOREVER);
	}
	else
	{
		PrintToChat(client,"\"Random choose\" is active. You can't change your model!");
	}
	
	return Plugin_Handled;
}

// Choose a random model for hiders
public Action:RandomModelChoose(client)
{	
	new String:info[256];
	new String:disp[256];
	new style = 0;
	new ModelCount = GetMenuItemCount(hModelMenu);
	new ModelID = GetRandomInt(0,ModelCount-1);
	
	PrintToServer("RandomChoose: Count: %i, ID: %i",ModelCount,ModelID);

	// Get Path from menueitem
	GetMenuItem(hModelMenu, ModelID, info, sizeof(info),style,disp, sizeof(disp));
	
	if(IsModelPrecached(info))
	{
		PrintToChat(client,"You are a \"%s\".",disp);
		PrintToChat(client,"Go and hide now!");
		SetEntityModel(client, info);
	}
}

public LoadMapModels(String:mapstr[256])
{
	new Handle:kv;
	new String:buffer[255];
	new String:model_name[255];
	new String:model_path[255];
	

	new String:filestr[256] = "cfg/hiddensm/models/";
	new String:defaultfilepath[256] = "cfg/hiddensm/models/default.txt";
	StrCat(filestr,gMaxLength,mapstr)
	StrCat(filestr, gMaxLength,".txt")
	
	
	if(!FileExists(filestr))
	{
		PrintToServer("[Hiddensm] Load Default Modelfile!");
		filestr = defaultfilepath;
		mapstr = "default";
	}
	
	if(FileExists(filestr))
	{
		kv = CreateKeyValues(mapstr);
		FileToKeyValues(kv, filestr)
	 	PrintToServer("[Hiddensm] Path: %s ", filestr);
		if (!KvGotoFirstSubKey(kv))
		{	
			PrintToServer("[Hiddensm] nothing found! %s",filestr)
			return
		}
	 	hModelMenu  = CreateMenu(HideItemMenuHandler);
		SetMenuTitle(hModelMenu , "Choose Model:");

		do
		{
			KvGetSectionName(kv, buffer, sizeof(buffer))
			PrintToServer("[Hiddensm] SectionName: Name: %s ", buffer)
			//if (i = x)
			//{
				//KvGotoNextKey(kv)
				KvGetString(kv, "name", model_name, gMaxLength);
				//KvGotoNextKey(kv)
				KvGetString(kv, "path", model_path, gMaxLength);

				PrecacheModel(model_path,true);
				AddFileToDownloadsTable(model_path);
				AddMenuItem(hModelMenu, model_path, model_name);
				PrintToServer("[Hiddensm] MenuItem: Name: %s Path: %s", model_name, model_path);
				
			//}
		} while (KvGotoNextKey(kv))
	 	SetMenuExitButton(hModelMenu, false);
		CloseHandle(kv)	
	}
	else
	{
		PrintToServer("[Hiddensm] Cannot Load Default Modelfile!");
	}
}

public RemoveWeaponsPlayerAll()
{
	new client;
	new client_team;
	
	for(new i=0;i<MAXPLAYERS;i++)
	{
		client = GetClientOfUserId(i);
		if(client > 0 && IsClientInGame(client))
		{
			if(IsPlayerAlive(client))
			{
				client_team = GetClientTeam(client);
				
				if(client_team == TEAM_1)
				{
					for(new x=0;x < 28;x++)
					{
						RemoveWeaponFromSlot(client, x);
					}
				}
			}
		}
	}
}

public bool:RemoveWeaponFromSlot(client, slot)
{
    //get the entity id of the weapon in the client's slot specified
    new bool:isRemoved;
    new weapon_entid = GetPlayerWeaponSlot(client,slot);
    //attempt to retrieve the weapon's entity id from the slot..
    if(weapon_entid >= 0)
    {
        //attempt to remove the weapon
        isRemoved = RemovePlayerItem(client,weapon_entid);
        //RemoveEdict(weapon_entid);
    }
    else
    {
        isRemoved = false;
    }
    return isRemoved;
}