#include <amxmodx>
#include <amxmisc>
#include <halomod>

#define PLUGIN "HaloMod Models"
#define VERSION HALOVERSION
#define AUTHOR "Soccdoodcss"

new gHasModel[33]
new gModel[33][32]

new tModel[] = "halored"
new ctModel[] = "haloblue"

public plugin_precache()
{
	precache_model("models/player/halored/halored.mdl")
	precache_model("models/player/haloblue/haloblue.mdl")
}

public plugin_init()
{
	register_plugin(PLUGIN, VERSION, AUTHOR)
	
	register_event("RoundTime", "onRound", "be")
	
	register_forward(FM_SetClientKeyValue,"fw_SetClientKeyValue")
	register_forward(FM_ClientUserInfoChanged,"fw_ClientUserInfoChanged")
}

public onRound(id)
{
	if(!is_user_alive(id) || !is_halo_on())
		return PLUGIN_HANDLED
	
	if(get_user_team(id) == 1)
		gModel[id] = tModel
	else if(get_user_team(id) == 2)
		gModel[id] = ctModel
	
	new currentmodel[32];  // get current model
	fm_get_user_model(id, currentmodel, sizeof currentmodel - 1);	
	
	if(!equal(currentmodel, gModel[id])) // check whether it matches the custom model
	{
		fm_set_user_model(id, gModel[id])
	}
	
	return PLUGIN_HANDLED
	
}

public fw_SetClientKeyValue(id, infobuffer, key[], value[])
{   
	if (gHasModel[id] && equal(key, "model") && is_halo_on())
		return FMRES_SUPERCEDE
	
	return FMRES_HANDLED
}

public fw_ClientUserInfoChanged(id, infobuffer)
{	
	if (!gHasModel[id] || !is_halo_on())
		return FMRES_HANDLED
	
	new currentmodel[32]
	fm_get_user_model(id, currentmodel, sizeof currentmodel - 1)
	
	if(!equal(currentmodel, gModel[id]))
		fm_set_user_model(id, gModel[id])
	
	return FMRES_HANDLED
}

stock fm_set_user_model(id, model[])
{   
	if(is_user_alive(id))
	{
		engfunc(EngFunc_SetClientKeyValue, id, engfunc(EngFunc_GetInfoKeyBuffer, id), "model", model)
		gHasModel[id] = 1
	}
}

stock fm_get_user_model(id, model[], len)
{   
	if(is_user_alive(id))
	{
		engfunc(EngFunc_InfoKeyValue, engfunc(EngFunc_GetInfoKeyBuffer, id), "model", model, len)
	}
}

stock fm_reset_user_model(id)
{
	if(is_user_alive(id))
	{
		gHasModel[id] = 0
		dllfunc(DLLFunc_ClientUserInfoChanged, id, engfunc(EngFunc_GetInfoKeyBuffer, id))
	}
}
