
////////////////////////////////////////
//
//  HLStats Ranks plugin by Johnny.
//
////////////////////////////////////////
//
// This plugin catches the /rank, /skill, 
// /top15 say commands and returns 
// the information from the HLStats database.
// 
// By the way, I am a god. 
//
// Thanks to JustinHomi's hlstats_skill plugin for
// showing proper use of multithreading and mysql
// modules.
//
// CMDS:
//    say /top15   -- Displays top15 players from HLStats.
//    say /skill   -- Displays player's rank from HLStats.
//    say /rank    -- Same as /skill
//
// CVARS:
//    amx_hlstats_host       -- HLStats database host (IP address)
//    amx_hlstats_user       -- HLStats database user login name.
//    amx_hlstats_pass       -- HLStats database password.
//    amx_hlstats_db         -- HLStats database name
//    amx_hlstats_prefix     -- HLStats database table prefix
//    amx_hlstats_reportall  -- Display rank to inquiring player or everyone?
//
////////////////////////////////////////

#include <amxmod>
#include <amxmisc>
#include <mysql>
#include <mthread>

new mhost[64]
new muser[32]
new mpass[32]
new mdb[32]
new mprefix[16]
new mysql = 0

public sql_init()
{
	new merror[32]	

	// Get database connectivity values.
	get_cvar_string("amx_hlstats_host",mhost,63)
	get_cvar_string("amx_hlstats_user",muser,31)
	get_cvar_string("amx_hlstats_pass",mpass,31)
	get_cvar_string("amx_hlstats_db",mdb,31)
	get_cvar_string("amx_hlstats_prefix",mprefix,15)

	// Attempt connection.
	mysql = mysql_connect(mhost,muser,mpass,mdb,merror,31)

	// Display result.
	if(mysql < 1)
	{
		server_print("[AMX] MySQL error : could not connect : '%s'",merror)
	}
	else
	{
		server_print("[AMX] HLstats Top15 successfully connected.")
	}

	return PLUGIN_CONTINUE
}

public say_skill(id)
{
	new idx[2]
	new tid

	// Make player ID a string.
	idx[0] = id
	// Attempt to create a thread/
	tid = thread_run("skill_thread",idx,2,"",THREAD_SYSPRIO_LOW,THREAD_QUEUE_LOCAL)

	if(!tid)
	{
		// Failure.
		server_print("[HLSTATS] Skill: failure creating thread!")
	}
	return PLUGIN_CONTINUE
}

public skill_thread(tid,idx[])
{
	new id = idx[0]
	new authid[17]
	new totalplayers[16]
	new query[256]
	new merror[32]
	new skill[10]
	new rank[16]
	new name[64]

	// Get user's authid.
	get_user_authid(id,authid,16)

	// Build query string.
	format(query,255,"select a.skill from %sPlayers a,%sPlayerUniqueIds b where a.playerId=b.playerId and \
		b.uniqueId='%s'",mprefix,mprefix,authid)

	// Attempt to execute query.
	mysql_query(mysql,query)
	
	// Handle any errors.
	mysql_error(mysql,merror,31)
	if (merror[0])
	{
		server_print("[AMX] MYSQL error: %s",merror)
		return PLUGIN_HANDLED
	}

	// Get the player's skill if it exists.
	if(mysql_nextrow(mysql)>0)
	{
		mysql_getfield(mysql,1,skill,9)
	}

	// Build query string.
	format(query,255,"select count(skill) from %sPlayers where skill >=%s and hideranking=0",mprefix,skill)

	// Attempt to execute query.
	mysql_query(mysql,query)

	// Handle any errors.
	mysql_error(mysql,merror,31)
	if (merror[0])
	{
		server_print("[AMX] MYSQL error: %s",merror)
		return PLUGIN_HANDLED
	}

	// Get the player's rank if it exists.
	if(mysql_nextrow(mysql)>0)
	{
		mysql_getfield(mysql,1,rank,15)
	}

	// Build query string.
	format(query,128,"select count(skill) from %sPlayers",mprefix)

	// Attempt to execute query.
	mysql_query(mysql,query)

	// Handle any errors.
	mysql_error(mysql,merror,31)
	if (merror[0])
	{
		server_print("[AMX] MYSQL error: %s",merror)
		return PLUGIN_HANDLED
	}

	// Get the total players if it exists.
	if(mysql_nextrow(mysql)>0)
	{
		mysql_getfield(mysql,1,totalplayers,15)
	}

	get_user_name(id,name,63)
	if (get_cvar_num("amx_hlstats_reportall") == 0)
	{
		// Report to player only.
		client_print(id, print_chat, "[HLSTATS] you are ranked %s of %s with %s points!", rank, totalplayers, skill)
	}
	else
	{
		// Report to everybody.
		// Get the player's name
		client_print(0, print_chat, "[HLSTATS] %s is ranked %s of %s with %s points!", name, rank, totalplayers, skill)
	}
	return PLUGIN_HANDLED
}

public say_top15(id)
{
	new idx[2]
	new tid

	// Make player ID a string.
	idx[0] = id
	// Attempt to create a thread/
	tid = thread_run("top15_thread",idx,2,"",THREAD_SYSPRIO_LOW,THREAD_QUEUE_LOCAL)

	if(!tid)
	{
		// Failure.
		server_print("[HLSTATS] Skill: failure creating thread!")
	}
	return PLUGIN_CONTINUE
}

public top15_thread(tid,idx[])
{
	new id = idx[0]
	new merror[32]
	new query[256]
	new buffer[2048]
	new rank = 0
	new line[256]

	new name[65]
	new skill[10]
	new kills[10]
	new deaths[10]

	// Build query string.
	format(query,255,"SELECT lastName, skill, kills, deaths \
				FROM %sPlayers \
				ORDER BY skill DESC \
				LIMIT 15", mprefix)

	// Execute query.
	mysql_query(mysql,query)
	mysql_error(mysql,merror,31)
	if (merror[0])
	{
		// 
		server_print("[AMX] MYSQL error: %s",merror)
		return PLUGIN_HANDLED
	}

	// Header.
	// copy(buffer,2047,"#   Skill      Kills/Deaths    Nick^n")
	copy(buffer,2047,"#   Skill      Nick^n")

	// Add each of the top 15 players to the buffer.
	while(mysql_nextrow(mysql)>0)
	{
		rank++
		mysql_getfield(mysql,1,name,64)
		mysql_getfield(mysql,2,skill,9)
		mysql_getfield(mysql,3,kills,9)
		mysql_getfield(mysql,4,deaths,9)

//		format(line, 255, "%d.  %s  %s/%s  %s^n", rank, skill, kills, deaths, name)
		format(line, 255, "%d.  %s  %s^n", rank, skill, name)

		add(buffer,2047, line)
	}

	// Show it to the player.
	show_motd(id,buffer,"Top 15")

	return PLUGIN_HANDLED
}

public plugin_end()
{
	if (mysql > 0)
	{
		// Close the database connection.
		mysql_close(mysql)
	}
	return PLUGIN_CONTINUE
}


public plugin_init(){
	// Register the plugin.	
	register_plugin("HLStats Ranks","1.0.0","Johnny")

	// Register the say commands.
	register_clcmd("say /top15","say_top15")
	register_clcmd("say_team /top15","say_top15")
	register_clcmd("say /skill","say_skill")
	register_clcmd("say_team /skill","say_skill")
	register_clcmd("say /rank","say_skill")
	register_clcmd("say_team /rank","say_skill")

	// Register the cvars.
	register_cvar("amx_hlstats_host","127.0.0.1")
	register_cvar("amx_hlstats_user","root")
	register_cvar("amx_hlstats_pass","pass")
	register_cvar("amx_hlstats_db","hlstats")
	register_cvar("amx_hlstats_prefix","hlstats_")
	register_cvar("amx_hlstats_reportall","1")

	// Delay mySQL access initialization.
	set_task(3.0,"sql_init")
	return PLUGIN_CONTINUE
}

