#include <amxmodx>
#include <amxmisc>
#include <kz>

/*
 * Credits to OneEyed. Using parts of his fake bot plugin to create this plugins.
 *
 * More to come.
 *
 *
 */

#define _TEAM_T 1
#define _TEAM_CT 2

// Holds bots id
new bot;

// Fake Bots Names
new bot_name[32] = "KZ Fake Player CT";

// Cvar Pointer.
new kz_enabled;

public plugin_init()
{
	register_plugin("Kz Fake Player", KZ_VERSION, "teame06");
	kz_enabled = get_cvar_pointer("kz_enabled");
}

public kz_Init(_state)
{
	if(!_state)
	{
		_kick_bot();
		pause("a");
		return;
	}

	if(!get_pcvar_num(kz_enabled))
	{
		_kick_bot();
		return;
	}
}

_kick_bot()
{
	if(bot)
		server_cmd("kick #%d", get_user_userid(bot));

	server_exec();
}

public RoundStart()
{
	if(!get_pcvar_num(kz_enabled))
		return;

	new players[32], nums;
	get_players(players, nums, "d");

	if(!bot && !nums)
		_make_player(_TEAM_CT);

	set_task(0.5, "delay_bot_settings"); // Delay for kz_plugin to set the cvar is_kz_map.
}

public delay_bot_settings()
{
	if(get_pcvar_num(kz_enabled))
	{
		if(!is_user_alive(bot))
			dllfunc(DLLFunc_Spawn, bot);

		if(bot)
			_bot_settings(bot);
	}
}

_bot_settings(botid)
{
	set_pev(botid, pev_effects, (pev(bot, pev_effects) | 128));
	set_pev(botid, pev_solid, SOLID_NOT);
	set_pev(botid, pev_takedamage, 0.0);
	cs_set_user_deaths(botid, -1000);
	set_pev(botid, pev_frags, -1000.0);

	if(cs_get_user_team(botid) != CS_TEAM_CT)
		cs_set_user_team(botid, CS_TEAM_CT, CS_CT_URBAN);
}

_make_player(_team)
{
	if(get_pcvar_num(kz_enabled))
	{
		if(!bot)
		{
			new reject[128];
			new botid = bot = engfunc(EngFunc_CreateFakeClient, bot_name);

			if(botid)
			{
				set_user_info(botid, "*bot", "1"); // Credit to strelomet (YaPB) for finding this.

				dllfunc(DLLFunc_ClientConnect, botid, bot_name, "127.0.0.1", reject);
				dllfunc(DLLFunc_ClientPutInServer, botid);

				cs_set_user_team(botid, _team, (_team == 2) ? CS_CT_URBAN : CS_T_TERROR);
				set_user_flags(botid, ADMIN_IMMUNITY);
			}
			else
				log_amx("Failed to create %s bot", bot_name);
		}
	}
}