#pragma semicolon 1

#include <sourcemod>
#include <cstrike>
#include <AFKManager>
#include <mapchooser_extended>

#pragma newdecls required

int g_iAdminAFKTime;
int g_iSelfMaxExtendsAmount;
int g_iSelfExtendsTime;
float g_fSelfExtendsRatio;
float g_fSelfExtendsDelay;

bool g_bSelfExtends[MAXPLAYERS + 1] = { false, ...};
bool g_bSelfExtendsAllowed;
bool g_bActiveAdmin[MAXPLAYERS + 1] = { false, ...};
int g_iSelfExtends;

ConVar g_cvarTimeLimit;

public Plugin myinfo =
{
	name = "No Admin Tools",
	author = "Dogan",
	description = "Make it possible for the server to do several things when there is no active admin online",
	version = "1.1.0",
	url = ""
};

public void OnPluginStart()
{
	RegAdminCmd("sm_checkadmins", Command_DisplayActiveAdmins, ADMFLAG_GENERIC, "Check if there are any active Admins online or not.");
	RegConsoleCmd("sm_selfextend", Command_SelfExtend, "Is available when all regular extends are depleted and there is no active admin online. Makes it possible for players to extend the map themselves");

	ConVar cvar;
	HookConVarChange((cvar = CreateConVar("sm_admin_afk_time", "30", "Time in seconds until an admin is considered as AFK.")), Cvar_AdminAFKTime);
	g_iAdminAFKTime = cvar.IntValue;
	HookConVarChange((cvar = CreateConVar("sm_selfextend_amount", "2", "Amount of sm_selfextend's allowed.")), Cvar_SelfExtendsAmount);
	g_iSelfMaxExtendsAmount = cvar.IntValue;
	HookConVarChange((cvar = CreateConVar("sm_selfextend_time", "10", "How long to extend in minutes when sm_selfextend passes through.")), Cvar_SelfExtendsTime);
	g_iSelfExtendsTime = cvar.IntValue;
	HookConVarChange((cvar = CreateConVar("sm_selfextend_ratio", "0.6", "Ratio needed for sm_selfextend to pass through.")), Cvar_SelfExtendsRatio);
	g_fSelfExtendsRatio = cvar.FloatValue;
	HookConVarChange((cvar = CreateConVar("sm_selfextend_delay", "60.0", "Time to pass until sm_selfextend can be used")), Cvar_SelfExtendsDelay);
	g_fSelfExtendsDelay = cvar.FloatValue;
	delete cvar;

	g_cvarTimeLimit = FindConVar("mp_timelimit");

	AutoExecConfig();
}

public void Cvar_AdminAFKTime(ConVar convar, const char[] oldValue, const char[] newValue)
{
	g_iAdminAFKTime = convar.IntValue;
}

public void Cvar_SelfExtendsAmount(ConVar convar, const char[] oldValue, const char[] newValue)
{
	g_iSelfMaxExtendsAmount = convar.IntValue;
}

public void Cvar_SelfExtendsTime(ConVar convar, const char[] oldValue, const char[] newValue)
{
	g_iSelfExtendsTime = convar.IntValue;
}

public void Cvar_SelfExtendsRatio(ConVar convar, const char[] oldValue, const char[] newValue)
{
	g_fSelfExtendsRatio = convar.FloatValue;
}

public void Cvar_SelfExtendsDelay(ConVar convar, const char[] oldValue, const char[] newValue)
{
	g_fSelfExtendsDelay = convar.FloatValue;
}

public bool ActiveAdmin(int client)
{
	if(GetClientIdleTime(client) < g_iAdminAFKTime)
		return true;

	return false;
}

public void OnClientDisconnect(int client)
{
	g_bSelfExtends[client] = false;
	g_bActiveAdmin[client] = false;

	CheckRatio();
}

public void OnClientPostAdminCheck(int client)
{
	if(CheckCommandAccess(client, "", ADMFLAG_GENERIC))
	{
		g_bActiveAdmin[client] = true;
	}
}

public void OnMapStart()
{
	g_iSelfExtends = 0;
	g_bSelfExtendsAllowed = false;

	CreateTimer(g_fSelfExtendsDelay, Timer_DelaySelfExtend, _, TIMER_FLAG_NO_MAPCHANGE);

	for(int i; i <= MaxClients; i++)
		g_bSelfExtends[i] = false;
}

public void OnMapEnd()
{
	g_bSelfExtendsAllowed = false;
}

public Action Timer_DelaySelfExtend(Handle timer)
{
	g_bSelfExtendsAllowed = true;
}

public Action Command_DisplayActiveAdmins(int client, int args)
{
	for(int i = 1; i <= MaxClients; i++)
		if(IsValidClient(i) && CheckCommandAccess(i, "", ADMFLAG_GENERIC) && ActiveAdmin(i))
			g_bActiveAdmin[i] = true;
		else if(IsValidClient(i) && CheckCommandAccess(i, "", ADMFLAG_GENERIC) && !ActiveAdmin(i))
			g_bActiveAdmin[i] = false;

	char aBuf[1024];
	char bBuf[1024];
	char aBuf2[MAX_NAME_LENGTH];

	for(int i = 1; i <= MaxClients; i++)
	{
		if(IsValidClient(i))
		{
			if(g_bActiveAdmin[i])
			{
				GetClientName(i, aBuf2, sizeof(aBuf2));
				StrCat(aBuf, sizeof(aBuf), aBuf2);
				StrCat(aBuf, sizeof(aBuf), ", ");
			}

			if(CheckCommandAccess(i, "", ADMFLAG_GENERIC) && !g_bActiveAdmin[i])
			{
				GetClientName(i, aBuf2, sizeof(aBuf2));
				StrCat(bBuf, sizeof(bBuf), aBuf2);
				StrCat(bBuf, sizeof(bBuf), ", ");
			}
		}
	}

	if(strlen(aBuf))
	{
		aBuf[strlen(aBuf) - 2] = 0;
		ReplyToCommand(client, "[SM] Active Admins online: %s", aBuf);
	}
	else
		ReplyToCommand(client, "[SM] Active Admins online: none");

	if(strlen(bBuf))
	{
		bBuf[strlen(bBuf) - 2] = 0;
		ReplyToCommand(client, "[SM] Inactive Admins online: %s", bBuf);
	}
	else
		ReplyToCommand(client, "[SM] Inactive Admins online: none");

	return Plugin_Handled;
}

public Action Command_SelfExtend(int client, int args)
{
	int iAdminActivity = 0;
	for(int i = 1; i <= MaxClients; i++)
		if(g_bActiveAdmin[i])
			iAdminActivity++;

	if(GetExtendsLeft() > 0)
	{
		ReplyToCommand(client, "[SM] Not available because not all regular extends have been depleted.");
		return Plugin_Handled;
	}
	if(iAdminActivity > 0)
	{
		ReplyToCommand(client, "[SM] Not available because there is atleast one active Admin who can extend. Please ask the Admins.");
		return Plugin_Handled;
	}
	if(!g_bSelfExtendsAllowed)
	{
		ReplyToCommand(client, "[SM] Not available because it's still too early in the map.");
		return Plugin_Handled;
	}
	if(g_iSelfMaxExtendsAmount <= g_iSelfExtends)
	{
		ReplyToCommand(client, "[SM] Not available because this map was already self-extended %d times.", g_iSelfMaxExtendsAmount);
		return Plugin_Handled;
	}

	if(!g_bSelfExtends[client])
	{
		g_bSelfExtends[client] = true;
		PrintToChatAll("[SM] %N wants to self-extend the map.", client);
		CheckRatio();
	}
	else
		ReplyToCommand(client, "[SM] You have already voted to self-extend the map.");

	return Plugin_Handled;
}

public void CheckRatio()
{
	if(!g_bSelfExtendsAllowed)
		return;

	int iPlayers;
	int iSelfExtendsPlayers;
	int iPlayersNeeded;

	for(int i = 1; i <= MaxClients; i++)
	{
		if(IsValidClient(i))
			iPlayers++;

		if(g_bSelfExtends[i])
			iSelfExtendsPlayers++;
	}

	iPlayersNeeded = RoundToFloor(float(iPlayers) * g_fSelfExtendsRatio);

	if(iSelfExtendsPlayers >= iPlayersNeeded && iPlayersNeeded != 0)
	{
		PrintToChatAll("[SM] Enough Players voted to self-extend the map. Adding %d minutes to the timelimit.", g_iSelfExtendsTime);
		LogMessage("Enough Players voted to self-extend the map. Adding %d minutes to the timelimit.", g_iSelfExtendsTime);
		g_iSelfExtends++;
		g_cvarTimeLimit.IntValue += g_iSelfExtendsTime;

		for(int j; j <= MaxClients; j++)
			g_bSelfExtends[j] = false;
	}

	return;
}

static stock bool IsValidClient(int client)
{
	if (client > 0 && client <= MaxClients && IsClientInGame(client))
	{
		return true;
	}
	else
	{
		return false;
	}
}