Missed a parameter that should have been const

/*
 * Copyright (c) 2016 Alex "ZeroKnight" George
 *
 * This file is licensed under the MIT License. For details, please see the
 * LICENSE file that should be included with the source code, or
 * <https://opensource.org/licenses/MIT>
 */

#include <sourcemod>

#pragma semicolon 1
#pragma newdecls required

char PLUGIN_NAME[]    = "Multi-Giveaway";
char PLUGIN_AUTHOR[]  = "Alex \"ZeroKnight\" George";
char PLUGIN_DESC[]    = "Expansive Giveaway system with numerous types of Giveaway events and stats";
char PLUGIN_VERSION[] = "0.2.0";
char PLUGIN_URL[]     = "http:/github.com/ZeroKnight/sm-Multi-Giveaway";
char PLUGIN_TAG[]     = "[MG]";

public Plugin myinfo =
{
  name        = PLUGIN_NAME,
  author      = PLUGIN_AUTHOR,
  description = PLUGIN_DESC,
  version     = PLUGIN_VERSION,
  url         = PLUGIN_URL
};

const int TYPEOPT_MAX_LEN = 64;

/* NOTE: (<<= 1) is actually a neat thing that SourcePawn does. It lets you
 * specify how to 'increment' each enumeration. In this case, each one will be
 * the previous value left shifted 1, which gives us our bit-field.
 */
enum GiveawayType (<<= 1)
{
  GT_Invalid = -1, GT_Dice = 1, GT_Number, GT_Kill, GT_All = 7
};
const int nGTypes = 3;

// Global state variables/data structures
StringMap GiveawayData;
ArrayList Dice_PlayerRolls;
ArrayList Dice_ReRolls;
ArrayList Number_PlayerGuesses;

ArrayList Current_TypeOpts; // NOTE: Subject to change

//File configfile = ...

// TODO: Put things like this in a personal core library?
#define CVAR(%1) ConVar cv_%1
char CVAR_PREFIX[] = "multi_giveaway";
CVAR(version);
CVAR(flags);
CVAR(enabled_types);
CVAR(player_state);
CVAR(min_conn_time);
CVAR(dice_min);
CVAR(dice_max);
CVAR(dice_show_rolls);
CVAR(dice_rerolls);
CVAR(number_min);
CVAR(number_max);
CVAR(number_show_guesses);

int abs(const int i) { return (i > 0) ? i : -i; }
int min(const int i, const int k) { return (i < k) ? i : k; }
int max(const int i, const int k) { return (i > k) ? i : k; }
int clamp(const int i, const int minval, const int maxval)
{
  return max(minval, min(i, maxval));
}

void RegisterConVars()
{
  // NOTE: Use HookConVarChange() for anything that needs it

  // XXX: Function overloads would be nice. Or casting that worked on strings.
  char sGT_All[32]; IntToString(view_as<int>(GT_All), sGT_All, sizeof(sGT_All));

  /* Core */
  cv_version = CreateConVar(
    "multi_giveaway_version",
    PLUGIN_VERSION,
    "Plugin version",
    FCVAR_SPONLY|FCVAR_REPLICATED|FCVAR_NOTIFY|FCVAR_DONTRECORD);
  cv_flags = CreateConVar(
    "multi_giveaway_flags",
    "b",
    "List of admin flags allowed to manage giveaways");
  cv_enabled_types = CreateConVar(
    "multi_giveaway_enabled_types",
    sGT_All,
    "Bit-field (sum of options) of enabled Giveaway types",
    FCVAR_NONE,
    true, 1.0,
    true, float(GT_All));
  cv_player_state = CreateConVar(
    "multi_giveaway_player_state",
    "2",
    "Player states eligible for Giveaway participation; each setting includes the previous one: 0 - Alive only, 1 - Dead, 2 - Spectator",
    FCVAR_NONE,
    true, 0.0,
    true, 2.0);
  cv_min_conn_time = CreateConVar( // TODO: Allow certain giveaways to override (eg. kill objective)
    "multi_giveaway_min_conn_time",
    "300", // 5 minutes
    "Amount of time in seconds a player must be connected to participate in a Giveaway",
    FCVAR_NONE,
    true, 0.0);

  /* Dice */
  cv_dice_min = CreateConVar(
    "multi_giveaway_dice_min",
    "1",
    "Lowest possible number a player may roll",
    FCVAR_NONE,
    true, 1.0);
  cv_dice_max = CreateConVar(
    "multi_giveaway_dice_max",
    "50",
    "Highest possible number a player may roll");
  cv_dice_show_rolls = CreateConVar(
    "multi_giveaway_dice_show_rolls",
    "0",
    "Who can see other clients' dice rolls: 0 - Nobody, 1 - Admins, 2 - Everyone",
    FCVAR_NONE,
    true, 0.0,
    true, 2.0);
  cv_dice_rerolls = CreateConVar(
    "multi_giveaway_dice_rerolls",
    "0",
    "Number of 'do-overs' a player gets when rolling. Only the last is counted, for better or for worse",
    FCVAR_NONE,
    true, 0.0);

  /* Number Guess */
  cv_number_min = CreateConVar(
    "multi_giveaway_number_min",
    "1",
    "Lower bound of the range of numbers",
    FCVAR_NONE,
    true, 1.0);
  cv_number_max = CreateConVar(
    "multi_giveaway_number_max",
    "100",
    "Upper bound of the range of numbers");
  cv_number_show_guesses = CreateConVar(
    "multi_giveaway_number_show_guesses",
    "2",
    "Who can see other clients' guesses: 0 - Nobody, 1 - Admins, 2 - Everyone",
    FCVAR_NONE,
    true, 0.0,
    true, 2.0);
}

void RegisterCommands()
{
  // XXX: Is there a better way to create aliases?
  // RegConsoleCmd for client commands (ie participation)
  // RegAdminCmd for admin commands (ie (start|stop)ing giveaways methodmap may
  // be helpful
  //
  // We can use AddCommandListener() to allow for "commands" that aren't
  // actually registered commands (think 'nominate')

  RegAdminCmd("sm_mg_reload", Command_ReloadConfig, ADMFLAG_CONFIG,
    "Reload configuration file");
  RegAdminCmd("sm_multigiveaway", Command_MultiGiveaway, ADMFLAG_GENERIC,
    "Manage giveaways");
  RegAdminCmd("sm_mg", Command_MultiGiveaway, ADMFLAG_GENERIC,
    "Manage giveaways");
  RegAdminCmd("sm_dice_rig", Command_Dice_Rig, ADMFLAG_CHEATS,
              "Rigs the Dice Giveaway so the chosen client wins");

  RegConsoleCmd("sm_rolldice", Command_Dice_Roll,
                "Rolls the dice during a Dice Giveaway");
  RegConsoleCmd("sm_reroll", Command_Dice_ReRoll,
                "Rolls the dice again during a Giveaway, giving you a new result (for better or worse!");
  RegConsoleCmd("sm_guess", Command_Number_Guess,
                "Guess a number for the Number-Guess Giveaway");
}

bool LoadConfig()
{
  //if (configfile != null) // is this boilerplate necessary?
    //CloseHandle(configfile);
  // ...
  return true;
}

void GetTypeName(const GiveawayType type, char[] str, const int sz)
{
  switch (type)
  {
    case GT_Invalid: return;
    case GT_Dice:    strcopy(str, sz, "Dice");
    case GT_Number:  strcopy(str, sz, "Number");
    case GT_Kill:    strcopy(str, sz, "Kill");
    default:         return;
  }
}

GiveawayType GetType(const char[] typename)
{
  if      (StrEqual(typename, "dice", false))   return GT_Dice;
  else if (StrEqual(typename, "number", false)) return GT_Number;
  else if (StrEqual(typename, "kill", false))   return GT_Kill;
  else return GT_Invalid;
}

bool IsTypeEnabled(const GiveawayType type)
{
  return view_as<GiveawayType>(cv_enabled_types.IntValue) & type ? true : false;
}

GiveawayType GetCurrentGiveaway()
{
  GiveawayType cg = GetCurrentGiveaway();
  return cg;
}

void SetCurrentGiveaway(const GiveawayType type)
{
  GiveawayData.SetValue("Current", type);
}

bool CanParticipate(const int client)
{
  bool spectating = GetClientTeam(client) == 1;

  /* Check player state */
  if (!IsPlayerAlive(client))
  {
    char phrase[32];
    switch (cv_player_state.IntValue)
    {
      case 0:
      {
        strcopy(phrase, sizeof(phrase),
                spectating ? "MG_Ineligible_Spec" : "MG_Ineligible_Alive");
      }
      case 1:
      {
        if (spectating)
          strcopy(phrase, sizeof(phrase), "MG_Ineligible_Spec");
      }
    }
    if (strlen(phrase))
    {
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, phrase);
      return false;
    }
  }

  /* Check connection time */
  float time = GetClientTime(client);
  int delta = cv_min_conn_time.IntValue - RoundToCeil(time);
  if (time < cv_min_conn_time.FloatValue)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Not_Connected_Long_Enough",
                   delta);
    return false;
  }
  return true;
}

void GetTypeOpts(char[] str, const int sz)
{
  char opt[64];
  for (int i = 0; i < Current_TypeOpts.Length; ++i)
  {
    Current_TypeOpts.GetString(i, opt, sizeof(opt));
    StrCat(str, sz, opt);
    StrCat(str, sz, "; ");
  }
}

void ArraySetAll(ArrayList& array, any value)
{
  for (int i = 0; i < array.Length; ++i)
    array.Set(i, value);
}

void SendToAdmins(const char[] str)
{
  for (int i = 1; i <= MaxClients; ++i)
  {
    if (IsClientInGame(i) && GetUserAdmin(i) != INVALID_ADMIN_ID)
      PrintToChat(i, "%s", str);
  }
}

bool Giveaway_Start(const GiveawayType type,
                    const ArrayList opts,
                    const int client,
                    const bool restarting=false)
{
  GiveawayType cg = GetCurrentGiveaway();
  char typename_current[32];
  GetTypeName(cg, typename_current, sizeof(typename_current));
  if (cg != GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Giveaway_In_Progress", typename_current);
    return false;
  }

  char typename[32], typeopts[512];
  GetTypeName(type, typename, sizeof(typename));
  GetTypeOpts(typeopts, sizeof(typeopts));
  if (type == GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Type_Invalid", typename);
    return false;
  }
  else if (!IsTypeEnabled(type) && !restarting)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Type_Disabled", typename);
    return false;
  }
  else if (type == GT_Kill) // XXX: Temporary
  {
    ReplyToCommand(client, "%s Not yet implemented!", PLUGIN_TAG);
    return false;
  }

  SetCurrentGiveaway(type);
  GiveawayData.SetValue("Participants", 0);
  GiveawayData.SetValue("Starter", client);

  if (!restarting)
  {
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Start", typename);
    LogAction(client, -1, "%L started Giveaway \"%s\" with options: %s", client, typename, typeopts);
  }
  switch (type)
  {
    case GT_Dice:
    {
      // TODO: Allow changing of "roll" command
      PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Dice_Start", "rolldice");
      if (cv_dice_rerolls.IntValue)
        PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Dice_ReRoll", "reroll");
    }
    case GT_Number:
    {
      int rand = GetRandomInt(cv_number_min.IntValue, cv_number_max.IntValue);
      GiveawayData.SetValue("Number_Target", rand);
      PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Number_Start", "guess", cv_number_min.IntValue, cv_number_max.IntValue);
    }
    case GT_Kill:
    {
    }
  }
  return true;
}

void Giveaway_Stop(const int client, const bool restarting=false)
{
  GiveawayType cg = GetCurrentGiveaway();
  if (cg == GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway");
    return;
  }

  char typename[32];
  GetTypeName(cg, typename, sizeof(typename));
  if (!restarting)
  {
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Stop", typename);
    LogAction(client, -1, "%L stopped Giveaway \"%s\"", client, typename);
  }

  int winner; GiveawayData.GetValue("Winner", winner);
  switch (cg)
  {
    case GT_Dice:
    {
      if (!restarting)
      {
        if (Dice_PlayerRolls.Length)
        {
          int bestroll = Dice_GetBestRoll();
          ArrayList tied = new ArrayList(1);
          int rigged; GiveawayData.GetValue("Winner", rigged);
          char name[MAX_NAME_LENGTH];

          /* Determine whether more than 1 player has the best roll */
          for (int i = 0; i < Dice_PlayerRolls.Length; ++i)
            if (Dice_PlayerRolls.Get(i) == bestroll) tied.Push(i);

          if (tied.Length > 1)
          {
            PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Giveaway_Tie");
            winner = tied.Get(GetRandomInt(0, tied.Length - 1));
          }
          else winner = tied.Get(0);

          /* Rig the Giveaway */
          if (rigged != -1) winner = rigged;

          GetClientName(winner, name, sizeof(name));
          PrintToChatAll("%s %t", PLUGIN_TAG,
                         bestroll == cv_dice_max.IntValue ?
                         "MG_Dice_Win_Perfect" : "MG_Dice_Win", name, bestroll);
        }
        else
          PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Giveaway_Cancelled", typename);
      }
      ArraySetAll(Dice_PlayerRolls, 0);
      ArraySetAll(Dice_ReRolls, cv_dice_rerolls.IntValue);
    }

    case GT_Number:
    {
      if (!restarting)
      {
        if (Number_PlayerGuesses.Length)
        {
          int target; GiveawayData.GetValue("Number_Target", target);
          char name[MAX_NAME_LENGTH];

          if (winner == -1)
          {
            /* Nobody guessed bang on, so find the closest */
            int closest = Number_GetClosestGuess();
            ArrayList tied = new ArrayList(1);

            /* Determine whether more than 1 player has the closest guess */
            for (int i = 0; i < Number_PlayerGuesses.Length; ++i)
              if (Number_PlayerGuesses.Get(i) == closest) tied.Push(i);

            if (tied.Length > 1)
            {
              PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Giveaway_Tie");
              winner = tied.Get(GetRandomInt(0, tied.Length - 1));
            }
            else winner = tied.Get(0);
            GetClientName(winner, name, sizeof(name));
            PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Number_Win_Close", name, closest, target);
          }
          else
          {
            GetClientName(winner, name, sizeof(name));
            PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Number_Win", name, target);
          }
        }
        else
          PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Giveaway_Cancelled", typename);
      }
      ArraySetAll(Number_PlayerGuesses, 0);
    }

    case GT_Kill:
    {
    }
  }
  SetCurrentGiveaway(GT_Invalid);
  GiveawayData.SetValue("Participants", -1);
  GiveawayData.SetValue("Starter", -1);
  GiveawayData.SetValue("Winner", -1);
  Current_TypeOpts.Clear();
}

void Giveaway_Restart(const int client)
{
  GiveawayType cg = GetCurrentGiveaway();
  if (cg == GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway");
    return;
  }

  char typename[32], typeopts[512];
  GetTypeName(cg, typename, sizeof(typename));
  GetTypeOpts(typeopts, sizeof(typeopts));

  ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Restart", typename);
  LogAction(client, -1, "%L restarted Giveaway \"%s\" with options: %s", client, typename, typeopts);
  Giveaway_Stop(client, true);
  Giveaway_Start(cg, Current_TypeOpts, client, true);
}

void Giveaway_Status(const int client)
{
  GiveawayType cg = GetCurrentGiveaway();
  if (cg == GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway");
    return;
  }

  char typename[32], typeopts[512];
  GetTypeName(cg, typename, sizeof(typename));
  GetTypeOpts(typeopts, sizeof(typeopts));

  ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Status", typename, typeopts);
  // do other things
}

void Dice_Roll(const int client, const bool rerolling=false)
{
  if (!rerolling && Dice_PlayerRolls.Get(client))
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_Rolled");
    if (cv_dice_rerolls.IntValue)
    {
      if (Dice_ReRolls.Get(client))
        ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll", "reroll");
      else
        ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll_None");
    }
    return;
  }

  int rand = GetRandomInt(cv_dice_min.IntValue, cv_dice_max.IntValue);
  int p; GiveawayData.GetValue("Participants", p);
  int rigged; GiveawayData.GetValue("Winner", rigged);

  if (!rerolling) GiveawayData.SetValue("Participants", ++p);

  // Make the rig look convincing
  if (rigged != -1 && client == rigged) rand = cv_dice_max.IntValue;

  Dice_PlayerRolls.Set(client, rand);

  char name[MAX_NAME_LENGTH];
  GetClientName(client, name, sizeof(name));
  switch (cv_dice_show_rolls.IntValue)
  {
    case 0:
    {
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_Result", "You", rand);
    }
    case 1:
    {
      char str[128];
      Format(str, sizeof(str), "%s %T", PLUGIN_TAG, "MG_Dice_Result", LANG_SERVER, name, rand);
      SendToAdmins(str);
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_Result", name, rand);
    }
    case 2:
    {
      PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Dice_Result", name, rand);
    }
  }
}

int Dice_GetBestRoll()
{
  int best = -1;
  for (int i = 0; i < Dice_PlayerRolls.Length; ++i)
  {
    int roll = Dice_PlayerRolls.Get(i);
    if (roll > best) best = roll;
  }
  return best;
}

int Number_GetClosestGuess()
{
  int closest = 0;
  int target; GiveawayData.GetValue("Number_Target", target);
  PrintToServer("target = %d", target);
  for (int i = 0; i < Number_PlayerGuesses.Length; ++i)
  {
    int guess = Number_PlayerGuesses.Get(i);
    if (guess == 0) continue; // No guess for this client
    int diff = abs(target - guess);
    int cdiff = abs(target - closest);
    if (closest == 0 || (diff < cdiff)) closest = guess;
  }
  return closest;
}

bool Number_IsGuessUnique(const int client, const int guess)
{
  for (int i = 0; i < Number_PlayerGuesses.Length; ++i)
    if (i != client && guess == Number_PlayerGuesses.Get(i)) return false;
  return true;
}

/***************************************************************\
 * SourceMod Callbacks
\***************************************************************/

public void OnPluginStart()
{
  // NOTE:
  // load our config. make use of the Kv*/KeyValue functions
  // for flag cvars, ReadFlagString(), GetUserFlagBits() and & are our friends
  // register event forwards (CreateGlobalForward())? ie kill-objectives

  RegisterCommands();
  RegisterConVars();

  char translatefile[64];
  Format(translatefile, sizeof(translatefile), "%s.phrases", PLUGIN_NAME);
  LoadTranslations(translatefile);
  LoadTranslations("common.phrases");
}

public void OnMapStart()
{
  /* Initialize global state and data structures */
  GiveawayData         = new StringMap();
  Current_TypeOpts     = new ArrayList(TYPEOPT_MAX_LEN);
  Dice_PlayerRolls     = new ArrayList(1, MAXPLAYERS);
  Dice_ReRolls         = new ArrayList(1, MAXPLAYERS);
  Number_PlayerGuesses = new ArrayList(1, MAXPLAYERS);

  SetCurrentGiveaway(GT_Invalid);
  GiveawayData.SetValue("Participants", -1);
  GiveawayData.SetValue("Starter", -1);
  GiveawayData.SetValue("Winner", -1);

  // Dice
  ArraySetAll(Dice_PlayerRolls, 0);
  // FIXME: Hook into convar change and re-set this array
  ArraySetAll(Dice_ReRolls, cv_dice_rerolls.IntValue);

  // Number Guess
  GiveawayData.SetValue("Number_Target", -1);
  ArraySetAll(Number_PlayerGuesses, 0);
}

public void OnClientDisconnect(int client)
{
  int p; GiveawayData.GetValue("Participants", p);
  int s; GiveawayData.GetValue("Starter", s);
  int w; GiveawayData.GetValue("Winner", w);
  GiveawayData.SetValue("Participants", p-1);
  if (s == client) GiveawayData.SetValue("Starter", -1);
  if (w == client) GiveawayData.SetValue("Winner", -1);

  // Dice
  Dice_PlayerRolls.Set(client, 0);

  // Number Guess
  Number_PlayerGuesses.Set(client, 0);
}

/***************************************************************\
 * Command Callbacks
\***************************************************************/

public Action Command_ReloadConfig(int client, int args)
{
  bool success = LoadConfig();
  LogAction(client, -1, "%s configuration reload by %L", PLUGIN_NAME, client);
  if (success)
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Config_Reloaded");
  else // TODO: Provide error information, etc
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Config_Error");

  return Plugin_Handled;
}

public Action Command_MultiGiveaway(int client, int args)
{
  // sm_mg [start|stop|restart|status] <dice|number|kill|...> [params]...

  if (!args)
  {
    // Interactive Mode: Menu-based interface
    ReplyToCommand(client, "%s Interactive mode not yet implemented!", PLUGIN_TAG);
    return Plugin_Handled;
  }

  char action[32], typename[32];
  GetCmdArg(1, action, sizeof(action));
  GetCmdArg(2, typename, sizeof(typename));
  GiveawayType type = GetType(typename);

  if (StrEqual(action, "start", false))
  {
    if (args < 2)
    {
      /* No type specified, inform client of valid types */
      char typenames[32*nGTypes];
      for (int i = 0; i < nGTypes; ++i)
      {
        char name[32];
        GetTypeName(view_as<GiveawayType>(1<<i), name, sizeof(name));
        StrCat(typenames, sizeof(typenames), name);
        StrCat(typenames, sizeof(typenames), ", ");
      }
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Type_Needed", typenames);
      return Plugin_Handled;
    }

    for (int i = 3; i <= GetCmdArgs(); ++i)
    {
      char opt[TYPEOPT_MAX_LEN];
      GetCmdArg(i, opt, sizeof(opt));
      Current_TypeOpts.PushString(opt);
    }
    Giveaway_Start(type, Current_TypeOpts, client);
  }
  else if (StrEqual(action, "stop", false))
    Giveaway_Stop(client);
  else if (StrEqual(action, "restart", false))
    Giveaway_Restart(client);
  else if (StrEqual(action, "status", false))
    Giveaway_Status(client);
  else
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Action_Invalid", action, "start, stop, restart, status");

  return Plugin_Handled;
}

public Action Command_Dice_Roll(int client, int args)
{
  if (!CanParticipate(client)) return Plugin_Handled;

  GiveawayType cg = GetCurrentGiveaway();
  if (cg != GT_Dice)
  {
    char typename[32];
    GetTypeName(GT_Dice, typename, sizeof(typename));
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway_Type", typename);
    return Plugin_Handled;
  }

  Dice_Roll(client);

  return Plugin_Handled;
}

public Action Command_Dice_ReRoll(int client, int args)
{
  if (!CanParticipate(client)) return Plugin_Handled;

  GiveawayType cg = GetCurrentGiveaway();
  if (cg != GT_Dice)
  {
    char typename[32];
    GetTypeName(GT_Dice, typename, sizeof(typename));
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway_Type", typename);
    return Plugin_Handled;
  }

  int rerolls = cv_dice_rerolls.IntValue;
  if (!rerolls)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll_Disabled");
    return Plugin_Handled;
  }
  if (!Dice_PlayerRolls.Get(client))
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll_Roll_Needed");
    return Plugin_Handled;
  }

  int rolls_left = Dice_ReRolls.Get(client);
  if (rolls_left)
  {
    int last_roll = Dice_PlayerRolls.Get(client);
    Dice_Roll(client, true);
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRolled", last_roll, --rolls_left);
    Dice_ReRolls.Set(client, rolls_left);
  }
  else
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll_None");

  return Plugin_Handled;
}

public Action Command_Dice_Rig(int client, int args)
{
  GiveawayType cg = GetCurrentGiveaway();
  if (cg != GT_Dice)
  {
    char typename[32];
    GetTypeName(GT_Dice, typename, sizeof(typename));
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway_Type", typename);
    return Plugin_Handled;
  }
  if (args < 1)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Target_Required");
    return Plugin_Handled;
  }

  char arg[MAX_NAME_LENGTH], target_name[MAX_NAME_LENGTH];
  int target[1];
  bool tnml;
  GetCmdArg(1, arg, sizeof(arg));
  int rv = ProcessTargetString(arg, client, target, 1, COMMAND_FILTER_CONNECTED,
                               target_name, sizeof(target_name), tnml);
  if (rv)
  {
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Dice_Rigged", target_name);
    GiveawayData.SetValue("Winner", target[0]);
  }
  else ReplyToTargetError(client, rv);

  return Plugin_Handled;
}

public Action Command_Number_Guess(int client, int args)
{
  if (!CanParticipate(client)) return Plugin_Handled;

  GiveawayType cg = GetCurrentGiveaway();
  if (cg != GT_Number)
  {
    char typename[32];
    GetTypeName(GT_Dice, typename, sizeof(typename));
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway_Type", typename);
    return Plugin_Handled;
  }
  if (args < 1)
  {
    ReplyToCommand(client, "%s Usage: sm_guess <number>", PLUGIN_TAG);
    return Plugin_Handled;
  }
  else if (Number_PlayerGuesses.Get(client))
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Guessed");
    return Plugin_Handled;
  }

  int guess;
  char arg[8];
  GetCmdArg(1, arg, sizeof(arg));

  if (!StringToIntEx(arg, guess))
  {
    ReplyToCommand(client, "%s Usage: sm_guess <number>", PLUGIN_TAG);
    return Plugin_Handled;
  }
  else if (guess >= cv_number_min.IntValue && guess <= cv_number_max.IntValue)
  {
    int p; GiveawayData.GetValue("Participants", p);
    int target; GiveawayData.GetValue("Number_Target", target);

    GiveawayData.SetValue("Participants", ++p);
    Number_PlayerGuesses.Set(client, guess);
    if (guess == target)
    {
      GiveawayData.SetValue("Winner", client);
      Giveaway_Stop(0);
    }
    else if (!Number_IsGuessUnique(client, guess))
    {
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Not_Unique");
      return Plugin_Handled;
    }
    else
    {
      char name[MAX_NAME_LENGTH];
      GetClientName(client, name, sizeof(name));
      switch (cv_number_show_guesses.IntValue)
      {
        case 0:
        {
          ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Guess", "You", guess);
        }
        case 1:
        {
          char str[128];
          Format(str, sizeof(str), "%s %T", PLUGIN_TAG, "MG_Number_Guess", LANG_SERVER, name, guess);
          SendToAdmins(str);
          ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Guess", name, guess);
        }
        case 2:
        {
          PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Number_Guess", name, guess);
        }
      }
    }
  }
  else
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Bad_Range", cv_number_min.IntValue, cv_number_max.IntValue);

  return Plugin_Handled;
}

// vim: et sts=2 sw=2

/*
 * Copyright (c) 2016 Alex "ZeroKnight" George
 *
 * This file is licensed under the MIT License. For details, please see the
 * LICENSE file that should be included with the source code, or
 * <https://opensource.org/licenses/MIT>
 */

#include <sourcemod>

#pragma semicolon 1
#pragma newdecls required

char PLUGIN_NAME[]    = "Multi-Giveaway";
char PLUGIN_AUTHOR[]  = "Alex \"ZeroKnight\" George";
char PLUGIN_DESC[]    = "Expansive Giveaway system with numerous types of Giveaway events and stats";
char PLUGIN_VERSION[] = "0.2.0";
char PLUGIN_URL[]     = "http:/github.com/ZeroKnight/sm-Multi-Giveaway";
char PLUGIN_TAG[]     = "[MG]";

public Plugin myinfo =
{
  name        = PLUGIN_NAME,
  author      = PLUGIN_AUTHOR,
  description = PLUGIN_DESC,
  version     = PLUGIN_VERSION,
  url         = PLUGIN_URL
};

const int TYPEOPT_MAX_LEN = 64;

/* NOTE: (<<= 1) is actually a neat thing that SourcePawn does. It lets you
 * specify how to 'increment' each enumeration. In this case, each one will be
 * the previous value left shifted 1, which gives us our bit-field.
 */
enum GiveawayType (<<= 1)
{
  GT_Invalid = -1, GT_Dice = 1, GT_Number, GT_Kill, GT_All = 7
};
const int nGTypes = 3;

// Global state variables/data structures
StringMap GiveawayData;
ArrayList Dice_PlayerRolls;
ArrayList Dice_ReRolls;
ArrayList Number_PlayerGuesses;

ArrayList Current_TypeOpts; // NOTE: Subject to change

//File configfile = ...

// TODO: Put things like this in a personal core library?
#define CVAR(%1) ConVar cv_%1
char CVAR_PREFIX[] = "multi_giveaway";
CVAR(version);
CVAR(flags);
CVAR(enabled_types);
CVAR(player_state);
CVAR(min_conn_time);
CVAR(dice_min);
CVAR(dice_max);
CVAR(dice_show_rolls);
CVAR(dice_rerolls);
CVAR(number_min);
CVAR(number_max);
CVAR(number_show_guesses);

int abs(const int i) { return (i > 0) ? i : -i; }
int min(const int i, const int k) { return (i < k) ? i : k; }
int max(const int i, const int k) { return (i > k) ? i : k; }
int clamp(const int i, const int minval, const int maxval)
{
  return max(minval, min(i, maxval));
}

void RegisterConVars()
{
  // NOTE: Use HookConVarChange() for anything that needs it

  // XXX: Function overloads would be nice. Or casting that worked on strings.
  char sGT_All[32]; IntToString(view_as<int>(GT_All), sGT_All, sizeof(sGT_All));

  /* Core */
  cv_version = CreateConVar(
    "multi_giveaway_version",
    PLUGIN_VERSION,
    "Plugin version",
    FCVAR_SPONLY|FCVAR_REPLICATED|FCVAR_NOTIFY|FCVAR_DONTRECORD);
  cv_flags = CreateConVar(
    "multi_giveaway_flags",
    "b",
    "List of admin flags allowed to manage giveaways");
  cv_enabled_types = CreateConVar(
    "multi_giveaway_enabled_types",
    sGT_All,
    "Bit-field (sum of options) of enabled Giveaway types",
    FCVAR_NONE,
    true, 1.0,
    true, float(GT_All));
  cv_player_state = CreateConVar(
    "multi_giveaway_player_state",
    "2",
    "Player states eligible for Giveaway participation; each setting includes the previous one: 0 - Alive only, 1 - Dead, 2 - Spectator",
    FCVAR_NONE,
    true, 0.0,
    true, 2.0);
  cv_min_conn_time = CreateConVar( // TODO: Allow certain giveaways to override (eg. kill objective)
    "multi_giveaway_min_conn_time",
    "300", // 5 minutes
    "Amount of time in seconds a player must be connected to participate in a Giveaway",
    FCVAR_NONE,
    true, 0.0);

  /* Dice */
  cv_dice_min = CreateConVar(
    "multi_giveaway_dice_min",
    "1",
    "Lowest possible number a player may roll",
    FCVAR_NONE,
    true, 1.0);
  cv_dice_max = CreateConVar(
    "multi_giveaway_dice_max",
    "50",
    "Highest possible number a player may roll");
  cv_dice_show_rolls = CreateConVar(
    "multi_giveaway_dice_show_rolls",
    "0",
    "Who can see other clients' dice rolls: 0 - Nobody, 1 - Admins, 2 - Everyone",
    FCVAR_NONE,
    true, 0.0,
    true, 2.0);
  cv_dice_rerolls = CreateConVar(
    "multi_giveaway_dice_rerolls",
    "0",
    "Number of 'do-overs' a player gets when rolling. Only the last is counted, for better or for worse",
    FCVAR_NONE,
    true, 0.0);

  /* Number Guess */
  cv_number_min = CreateConVar(
    "multi_giveaway_number_min",
    "1",
    "Lower bound of the range of numbers",
    FCVAR_NONE,
    true, 1.0);
  cv_number_max = CreateConVar(
    "multi_giveaway_number_max",
    "100",
    "Upper bound of the range of numbers");
  cv_number_show_guesses = CreateConVar(
    "multi_giveaway_number_show_guesses",
    "2",
    "Who can see other clients' guesses: 0 - Nobody, 1 - Admins, 2 - Everyone",
    FCVAR_NONE,
    true, 0.0,
    true, 2.0);
}

void RegisterCommands()
{
  // XXX: Is there a better way to create aliases?
  // RegConsoleCmd for client commands (ie participation)
  // RegAdminCmd for admin commands (ie (start|stop)ing giveaways methodmap may
  // be helpful
  //
  // We can use AddCommandListener() to allow for "commands" that aren't
  // actually registered commands (think 'nominate')

  RegAdminCmd("sm_mg_reload", Command_ReloadConfig, ADMFLAG_CONFIG,
    "Reload configuration file");
  RegAdminCmd("sm_multigiveaway", Command_MultiGiveaway, ADMFLAG_GENERIC,
    "Manage giveaways");
  RegAdminCmd("sm_mg", Command_MultiGiveaway, ADMFLAG_GENERIC,
    "Manage giveaways");
  RegAdminCmd("sm_dice_rig", Command_Dice_Rig, ADMFLAG_CHEATS,
              "Rigs the Dice Giveaway so the chosen client wins");

  RegConsoleCmd("sm_rolldice", Command_Dice_Roll,
                "Rolls the dice during a Dice Giveaway");
  RegConsoleCmd("sm_reroll", Command_Dice_ReRoll,
                "Rolls the dice again during a Giveaway, giving you a new result (for better or worse!");
  RegConsoleCmd("sm_guess", Command_Number_Guess,
                "Guess a number for the Number-Guess Giveaway");
}

bool LoadConfig()
{
  //if (configfile != null) // is this boilerplate necessary?
    //CloseHandle(configfile);
  // ...
  return true;
}

void GetTypeName(const GiveawayType type, char[] str, int sz)
{
  switch (type)
  {
    case GT_Invalid: return;
    case GT_Dice:    strcopy(str, sz, "Dice");
    case GT_Number:  strcopy(str, sz, "Number");
    case GT_Kill:    strcopy(str, sz, "Kill");
    default:         return;
  }
}

GiveawayType GetType(const char[] typename)
{
  if      (StrEqual(typename, "dice", false))   return GT_Dice;
  else if (StrEqual(typename, "number", false)) return GT_Number;
  else if (StrEqual(typename, "kill", false))   return GT_Kill;
  else return GT_Invalid;
}

bool IsTypeEnabled(const GiveawayType type)
{
  return view_as<GiveawayType>(cv_enabled_types.IntValue) & type ? true : false;
}

GiveawayType GetCurrentGiveaway()
{
  GiveawayType cg = GetCurrentGiveaway();
  return cg;
}

void SetCurrentGiveaway(const GiveawayType type)
{
  GiveawayData.SetValue("Current", type);
}

bool CanParticipate(const int client)
{
  bool spectating = GetClientTeam(client) == 1;

  /* Check player state */
  if (!IsPlayerAlive(client))
  {
    char phrase[32];
    switch (cv_player_state.IntValue)
    {
      case 0:
      {
        strcopy(phrase, sizeof(phrase),
                spectating ? "MG_Ineligible_Spec" : "MG_Ineligible_Alive");
      }
      case 1:
      {
        if (spectating)
          strcopy(phrase, sizeof(phrase), "MG_Ineligible_Spec");
      }
    }
    if (strlen(phrase))
    {
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, phrase);
      return false;
    }
  }

  /* Check connection time */
  float time = GetClientTime(client);
  int delta = cv_min_conn_time.IntValue - RoundToCeil(time);
  if (time < cv_min_conn_time.FloatValue)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Not_Connected_Long_Enough",
                   delta);
    return false;
  }
  return true;
}

void GetTypeOpts(char[] str, const int sz)
{
  char opt[64];
  for (int i = 0; i < Current_TypeOpts.Length; ++i)
  {
    Current_TypeOpts.GetString(i, opt, sizeof(opt));
    StrCat(str, sz, opt);
    StrCat(str, sz, "; ");
  }
}

void ArraySetAll(ArrayList& array, any value)
{
  for (int i = 0; i < array.Length; ++i)
    array.Set(i, value);
}

void SendToAdmins(const char[] str)
{
  for (int i = 1; i <= MaxClients; ++i)
  {
    if (IsClientInGame(i) && GetUserAdmin(i) != INVALID_ADMIN_ID)
      PrintToChat(i, "%s", str);
  }
}

bool Giveaway_Start(const GiveawayType type,
                    const ArrayList opts,
                    const int client,
                    const bool restarting=false)
{
  GiveawayType cg = GetCurrentGiveaway();
  char typename_current[32];
  GetTypeName(cg, typename_current, sizeof(typename_current));
  if (cg != GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Giveaway_In_Progress", typename_current);
    return false;
  }

  char typename[32], typeopts[512];
  GetTypeName(type, typename, sizeof(typename));
  GetTypeOpts(typeopts, sizeof(typeopts));
  if (type == GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Type_Invalid", typename);
    return false;
  }
  else if (!IsTypeEnabled(type) && !restarting)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Type_Disabled", typename);
    return false;
  }
  else if (type == GT_Kill) // XXX: Temporary
  {
    ReplyToCommand(client, "%s Not yet implemented!", PLUGIN_TAG);
    return false;
  }

  SetCurrentGiveaway(type);
  GiveawayData.SetValue("Participants", 0);
  GiveawayData.SetValue("Starter", client);

  if (!restarting)
  {
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Start", typename);
    LogAction(client, -1, "%L started Giveaway \"%s\" with options: %s", client, typename, typeopts);
  }
  switch (type)
  {
    case GT_Dice:
    {
      // TODO: Allow changing of "roll" command
      PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Dice_Start", "rolldice");
      if (cv_dice_rerolls.IntValue)
        PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Dice_ReRoll", "reroll");
    }
    case GT_Number:
    {
      int rand = GetRandomInt(cv_number_min.IntValue, cv_number_max.IntValue);
      GiveawayData.SetValue("Number_Target", rand);
      PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Number_Start", "guess", cv_number_min.IntValue, cv_number_max.IntValue);
    }
    case GT_Kill:
    {
    }
  }
  return true;
}

void Giveaway_Stop(const int client, const bool restarting=false)
{
  GiveawayType cg = GetCurrentGiveaway();
  if (cg == GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway");
    return;
  }

  char typename[32];
  GetTypeName(cg, typename, sizeof(typename));
  if (!restarting)
  {
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Stop", typename);
    LogAction(client, -1, "%L stopped Giveaway \"%s\"", client, typename);
  }

  int winner; GiveawayData.GetValue("Winner", winner);
  switch (cg)
  {
    case GT_Dice:
    {
      if (!restarting)
      {
        if (Dice_PlayerRolls.Length)
        {
          int bestroll = Dice_GetBestRoll();
          ArrayList tied = new ArrayList(1);
          int rigged; GiveawayData.GetValue("Winner", rigged);
          char name[MAX_NAME_LENGTH];

          /* Determine whether more than 1 player has the best roll */
          for (int i = 0; i < Dice_PlayerRolls.Length; ++i)
            if (Dice_PlayerRolls.Get(i) == bestroll) tied.Push(i);

          if (tied.Length > 1)
          {
            PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Giveaway_Tie");
            winner = tied.Get(GetRandomInt(0, tied.Length - 1));
          }
          else winner = tied.Get(0);

          /* Rig the Giveaway */
          if (rigged != -1) winner = rigged;

          GetClientName(winner, name, sizeof(name));
          PrintToChatAll("%s %t", PLUGIN_TAG,
                         bestroll == cv_dice_max.IntValue ?
                         "MG_Dice_Win_Perfect" : "MG_Dice_Win", name, bestroll);
        }
        else
          PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Giveaway_Cancelled", typename);
      }
      ArraySetAll(Dice_PlayerRolls, 0);
      ArraySetAll(Dice_ReRolls, cv_dice_rerolls.IntValue);
    }

    case GT_Number:
    {
      if (!restarting)
      {
        if (Number_PlayerGuesses.Length)
        {
          int target; GiveawayData.GetValue("Number_Target", target);
          char name[MAX_NAME_LENGTH];

          if (winner == -1)
          {
            /* Nobody guessed bang on, so find the closest */
            int closest = Number_GetClosestGuess();
            ArrayList tied = new ArrayList(1);

            /* Determine whether more than 1 player has the closest guess */
            for (int i = 0; i < Number_PlayerGuesses.Length; ++i)
              if (Number_PlayerGuesses.Get(i) == closest) tied.Push(i);

            if (tied.Length > 1)
            {
              PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Giveaway_Tie");
              winner = tied.Get(GetRandomInt(0, tied.Length - 1));
            }
            else winner = tied.Get(0);
            GetClientName(winner, name, sizeof(name));
            PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Number_Win_Close", name, closest, target);
          }
          else
          {
            GetClientName(winner, name, sizeof(name));
            PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Number_Win", name, target);
          }
        }
        else
          PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Giveaway_Cancelled", typename);
      }
      ArraySetAll(Number_PlayerGuesses, 0);
    }

    case GT_Kill:
    {
    }
  }
  SetCurrentGiveaway(GT_Invalid);
  GiveawayData.SetValue("Participants", -1);
  GiveawayData.SetValue("Starter", -1);
  GiveawayData.SetValue("Winner", -1);
  Current_TypeOpts.Clear();
}

void Giveaway_Restart(const int client)
{
  GiveawayType cg = GetCurrentGiveaway();
  if (cg == GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway");
    return;
  }

  char typename[32], typeopts[512];
  GetTypeName(cg, typename, sizeof(typename));
  GetTypeOpts(typeopts, sizeof(typeopts));

  ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Restart", typename);
  LogAction(client, -1, "%L restarted Giveaway \"%s\" with options: %s", client, typename, typeopts);
  Giveaway_Stop(client, true);
  Giveaway_Start(cg, Current_TypeOpts, client, true);
}

void Giveaway_Status(const int client)
{
  GiveawayType cg = GetCurrentGiveaway();
  if (cg == GT_Invalid)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway");
    return;
  }

  char typename[32], typeopts[512];
  GetTypeName(cg, typename, sizeof(typename));
  GetTypeOpts(typeopts, sizeof(typeopts));

  ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Status", typename, typeopts);
  // do other things
}

void Dice_Roll(const int client, const bool rerolling=false)
{
  if (!rerolling && Dice_PlayerRolls.Get(client))
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_Rolled");
    if (cv_dice_rerolls.IntValue)
    {
      if (Dice_ReRolls.Get(client))
        ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll", "reroll");
      else
        ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll_None");
    }
    return;
  }

  int rand = GetRandomInt(cv_dice_min.IntValue, cv_dice_max.IntValue);
  int p; GiveawayData.GetValue("Participants", p);
  int rigged; GiveawayData.GetValue("Winner", rigged);

  if (!rerolling) GiveawayData.SetValue("Participants", ++p);

  // Make the rig look convincing
  if (rigged != -1 && client == rigged) rand = cv_dice_max.IntValue;

  Dice_PlayerRolls.Set(client, rand);

  char name[MAX_NAME_LENGTH];
  GetClientName(client, name, sizeof(name));
  switch (cv_dice_show_rolls.IntValue)
  {
    case 0:
    {
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_Result", "You", rand);
    }
    case 1:
    {
      char str[128];
      Format(str, sizeof(str), "%s %T", PLUGIN_TAG, "MG_Dice_Result", LANG_SERVER, name, rand);
      SendToAdmins(str);
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_Result", name, rand);
    }
    case 2:
    {
      PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Dice_Result", name, rand);
    }
  }
}

int Dice_GetBestRoll()
{
  int best = -1;
  for (int i = 0; i < Dice_PlayerRolls.Length; ++i)
  {
    int roll = Dice_PlayerRolls.Get(i);
    if (roll > best) best = roll;
  }
  return best;
}

int Number_GetClosestGuess()
{
  int closest = 0;
  int target; GiveawayData.GetValue("Number_Target", target);
  PrintToServer("target = %d", target);
  for (int i = 0; i < Number_PlayerGuesses.Length; ++i)
  {
    int guess = Number_PlayerGuesses.Get(i);
    if (guess == 0) continue; // No guess for this client
    int diff = abs(target - guess);
    int cdiff = abs(target - closest);
    if (closest == 0 || (diff < cdiff)) closest = guess;
  }
  return closest;
}

bool Number_IsGuessUnique(const int client, const int guess)
{
  for (int i = 0; i < Number_PlayerGuesses.Length; ++i)
    if (i != client && guess == Number_PlayerGuesses.Get(i)) return false;
  return true;
}

/***************************************************************\
 * SourceMod Callbacks
\***************************************************************/

public void OnPluginStart()
{
  // NOTE:
  // load our config. make use of the Kv*/KeyValue functions
  // for flag cvars, ReadFlagString(), GetUserFlagBits() and & are our friends
  // register event forwards (CreateGlobalForward())? ie kill-objectives

  RegisterCommands();
  RegisterConVars();

  char translatefile[64];
  Format(translatefile, sizeof(translatefile), "%s.phrases", PLUGIN_NAME);
  LoadTranslations(translatefile);
  LoadTranslations("common.phrases");
}

public void OnMapStart()
{
  /* Initialize global state and data structures */
  GiveawayData         = new StringMap();
  Current_TypeOpts     = new ArrayList(TYPEOPT_MAX_LEN);
  Dice_PlayerRolls     = new ArrayList(1, MAXPLAYERS);
  Dice_ReRolls         = new ArrayList(1, MAXPLAYERS);
  Number_PlayerGuesses = new ArrayList(1, MAXPLAYERS);

  SetCurrentGiveaway(GT_Invalid);
  GiveawayData.SetValue("Participants", -1);
  GiveawayData.SetValue("Starter", -1);
  GiveawayData.SetValue("Winner", -1);

  // Dice
  ArraySetAll(Dice_PlayerRolls, 0);
  // FIXME: Hook into convar change and re-set this array
  ArraySetAll(Dice_ReRolls, cv_dice_rerolls.IntValue);

  // Number Guess
  GiveawayData.SetValue("Number_Target", -1);
  ArraySetAll(Number_PlayerGuesses, 0);
}

public void OnClientDisconnect(int client)
{
  int p; GiveawayData.GetValue("Participants", p);
  int s; GiveawayData.GetValue("Starter", s);
  int w; GiveawayData.GetValue("Winner", w);
  GiveawayData.SetValue("Participants", p-1);
  if (s == client) GiveawayData.SetValue("Starter", -1);
  if (w == client) GiveawayData.SetValue("Winner", -1);

  // Dice
  Dice_PlayerRolls.Set(client, 0);

  // Number Guess
  Number_PlayerGuesses.Set(client, 0);
}

/***************************************************************\
 * Command Callbacks
\***************************************************************/

public Action Command_ReloadConfig(int client, int args)
{
  bool success = LoadConfig();
  LogAction(client, -1, "%s configuration reload by %L", PLUGIN_NAME, client);
  if (success)
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Config_Reloaded");
  else // TODO: Provide error information, etc
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Config_Error");

  return Plugin_Handled;
}

public Action Command_MultiGiveaway(int client, int args)
{
  // sm_mg [start|stop|restart|status] <dice|number|kill|...> [params]...

  if (!args)
  {
    // Interactive Mode: Menu-based interface
    ReplyToCommand(client, "%s Interactive mode not yet implemented!", PLUGIN_TAG);
    return Plugin_Handled;
  }

  char action[32], typename[32];
  GetCmdArg(1, action, sizeof(action));
  GetCmdArg(2, typename, sizeof(typename));
  GiveawayType type = GetType(typename);

  if (StrEqual(action, "start", false))
  {
    if (args < 2)
    {
      /* No type specified, inform client of valid types */
      char typenames[32*nGTypes];
      for (int i = 0; i < nGTypes; ++i)
      {
        char name[32];
        GetTypeName(view_as<GiveawayType>(1<<i), name, sizeof(name));
        StrCat(typenames, sizeof(typenames), name);
        StrCat(typenames, sizeof(typenames), ", ");
      }
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Type_Needed", typenames);
      return Plugin_Handled;
    }

    for (int i = 3; i <= GetCmdArgs(); ++i)
    {
      char opt[TYPEOPT_MAX_LEN];
      GetCmdArg(i, opt, sizeof(opt));
      Current_TypeOpts.PushString(opt);
    }
    Giveaway_Start(type, Current_TypeOpts, client);
  }
  else if (StrEqual(action, "stop", false))
    Giveaway_Stop(client);
  else if (StrEqual(action, "restart", false))
    Giveaway_Restart(client);
  else if (StrEqual(action, "status", false))
    Giveaway_Status(client);
  else
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Action_Invalid", action, "start, stop, restart, status");

  return Plugin_Handled;
}

public Action Command_Dice_Roll(int client, int args)
{
  if (!CanParticipate(client)) return Plugin_Handled;

  GiveawayType cg = GetCurrentGiveaway();
  if (cg != GT_Dice)
  {
    char typename[32];
    GetTypeName(GT_Dice, typename, sizeof(typename));
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway_Type", typename);
    return Plugin_Handled;
  }

  Dice_Roll(client);

  return Plugin_Handled;
}

public Action Command_Dice_ReRoll(int client, int args)
{
  if (!CanParticipate(client)) return Plugin_Handled;

  GiveawayType cg = GetCurrentGiveaway();
  if (cg != GT_Dice)
  {
    char typename[32];
    GetTypeName(GT_Dice, typename, sizeof(typename));
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway_Type", typename);
    return Plugin_Handled;
  }

  int rerolls = cv_dice_rerolls.IntValue;
  if (!rerolls)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll_Disabled");
    return Plugin_Handled;
  }
  if (!Dice_PlayerRolls.Get(client))
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll_Roll_Needed");
    return Plugin_Handled;
  }

  int rolls_left = Dice_ReRolls.Get(client);
  if (rolls_left)
  {
    int last_roll = Dice_PlayerRolls.Get(client);
    Dice_Roll(client, true);
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRolled", last_roll, --rolls_left);
    Dice_ReRolls.Set(client, rolls_left);
  }
  else
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Dice_ReRoll_None");

  return Plugin_Handled;
}

public Action Command_Dice_Rig(int client, int args)
{
  GiveawayType cg = GetCurrentGiveaway();
  if (cg != GT_Dice)
  {
    char typename[32];
    GetTypeName(GT_Dice, typename, sizeof(typename));
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway_Type", typename);
    return Plugin_Handled;
  }
  if (args < 1)
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Target_Required");
    return Plugin_Handled;
  }

  char arg[MAX_NAME_LENGTH], target_name[MAX_NAME_LENGTH];
  int target[1];
  bool tnml;
  GetCmdArg(1, arg, sizeof(arg));
  int rv = ProcessTargetString(arg, client, target, 1, COMMAND_FILTER_CONNECTED,
                               target_name, sizeof(target_name), tnml);
  if (rv)
  {
    ShowActivity2(client, PLUGIN_TAG, " %t", "MG_Dice_Rigged", target_name);
    GiveawayData.SetValue("Winner", target[0]);
  }
  else ReplyToTargetError(client, rv);

  return Plugin_Handled;
}

public Action Command_Number_Guess(int client, int args)
{
  if (!CanParticipate(client)) return Plugin_Handled;

  GiveawayType cg = GetCurrentGiveaway();
  if (cg != GT_Number)
  {
    char typename[32];
    GetTypeName(GT_Dice, typename, sizeof(typename));
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_No_Giveaway_Type", typename);
    return Plugin_Handled;
  }
  if (args < 1)
  {
    ReplyToCommand(client, "%s Usage: sm_guess <number>", PLUGIN_TAG);
    return Plugin_Handled;
  }
  else if (Number_PlayerGuesses.Get(client))
  {
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Guessed");
    return Plugin_Handled;
  }

  int guess;
  char arg[8];
  GetCmdArg(1, arg, sizeof(arg));

  if (!StringToIntEx(arg, guess))
  {
    ReplyToCommand(client, "%s Usage: sm_guess <number>", PLUGIN_TAG);
    return Plugin_Handled;
  }
  else if (guess >= cv_number_min.IntValue && guess <= cv_number_max.IntValue)
  {
    int p; GiveawayData.GetValue("Participants", p);
    int target; GiveawayData.GetValue("Number_Target", target);

    GiveawayData.SetValue("Participants", ++p);
    Number_PlayerGuesses.Set(client, guess);
    if (guess == target)
    {
      GiveawayData.SetValue("Winner", client);
      Giveaway_Stop(0);
    }
    else if (!Number_IsGuessUnique(client, guess))
    {
      ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Not_Unique");
      return Plugin_Handled;
    }
    else
    {
      char name[MAX_NAME_LENGTH];
      GetClientName(client, name, sizeof(name));
      switch (cv_number_show_guesses.IntValue)
      {
        case 0:
        {
          ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Guess", "You", guess);
        }
        case 1:
        {
          char str[128];
          Format(str, sizeof(str), "%s %T", PLUGIN_TAG, "MG_Number_Guess", LANG_SERVER, name, guess);
          SendToAdmins(str);
          ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Guess", name, guess);
        }
        case 2:
        {
          PrintToChatAll("%s %t", PLUGIN_TAG, "MG_Number_Guess", name, guess);
        }
      }
    }
  }
  else
    ReplyToCommand(client, "%s %t", PLUGIN_TAG, "MG_Number_Bad_Range", cv_number_min.IntValue, cv_number_max.IntValue);

  return Plugin_Handled;
}

// vim: et sts=2 sw=2


Touch up nomfav

Touch up nomfav

/**
 * vim: set ts=4 :
 * =============================================================================
 * map_votes
 * Interact with the Map Votes web api - https://github.com/CrimsonTautology/map_votes
 *
 * Copyright 2013 The Crimson Tautology
 * =============================================================================
 *
 */

#pragma semicolon 1

#include <sourcemod>
#include <steamtools>
#include <base64>
#include <smjansson>

#define PLUGIN_VERSION "0.1"

public Plugin:myinfo = {
    name = "MapVotes",
    author = "CrimsonTautology",
    description = "Interact with the Map Votes web api",
    version = PLUGIN_VERSION,
    url = "https://github.com/CrimsonTautology/sm_map_votes"
};

#define CAST_VOTE_ROUTE "/v1/api/cast_vote"
#define WRITE_MESSAGE_ROUTE "/v1/api/write_message"
#define FAVORITE_ROUTE "/v1/api/favorite"
#define UNFAVORITE_ROUTE "/v1/api/unfavorite"
#define GET_FAVORITES_ROUTE "/v1/api/get_favorites"
#define HAVE_NOT_VOTED_ROUTE "/v1/api/have_not_voted"
#define SERVER_QUERY_ROUTE "/v1/api/server_query"
#define MAPS_ROUTE "/maps"

#define MAX_STEAMID_LENGTH 21
#define MAX_COMMUNITYID_LENGTH 18

new Handle:g_Cvar_MapVotesUrl = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesPort = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesApiKey = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesVotingEnabled = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesCommentingEnabled = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesNominationsName = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesRequestCooldownTime = INVALID_HANDLE;

new bool:g_IsInCooldown[MAXPLAYERS+1];

new g_MapFileSerial = -1;
new Handle:g_MapList = INVALID_HANDLE;
new Handle:g_MapTrie = INVALID_HANDLE;

new Handle:g_nominations = INVALID_HANDLE;
new Function:g_Handler_MapSelectMenu = INVALID_FUNCTION;

public OnPluginStart()
{

    g_Cvar_MapVotesUrl = CreateConVar("sm_map_votes_url", "", "URL to your Map Votes web page.  Remeber the \"http://\" part and to quote the entire url!");
    g_Cvar_MapVotesPort = CreateConVar("sm_map_votes_port", "80", "HTTP Port used");
    g_Cvar_MapVotesApiKey = CreateConVar("sm_map_votes_api_key", "", "The API key you generated to interact with the Map Votes web page");
    g_Cvar_MapVotesVotingEnabled = CreateConVar("sm_map_votes_voting_enabled", "1", "Whether players are allowed to vote on the current map");
    g_Cvar_MapVotesCommentingEnabled = CreateConVar("sm_map_votes_commenting_enabled", "1", "Whether players are allowed to comment on the current map");
    g_Cvar_MapVotesNominationsName = CreateConVar("sm_map_votes_nominations_plugin", "nominations.smx", "The nominations plugin used by the server");
    g_Cvar_MapVotesRequestCooldownTime = CreateConVar("sm_map_votes_request_cooldown_time", "2.0", "How long in seconds before a client can send another http request");

    RegConsoleCmd("sm_votemenu", Command_VoteMenu, "Bring up a menu to vote on the current map");
    RegConsoleCmd("sm_voteup", Command_VoteUp, "Vote that you like the current map");
    RegConsoleCmd("sm_like", Command_VoteUp, "Vote that you like the current map");
    RegConsoleCmd("sm_votedown", Command_VoteDown, "Vote that you hate the current map");
    RegConsoleCmd("sm_hate", Command_VoteDown, "Vote that you hate the current map");

    RegConsoleCmd("sm_fav", Command_Favorite, "Add this map to your favorites");
    RegConsoleCmd("sm_unfav", Command_Unfavorite, "Remove this map to your favorites");
    RegConsoleCmd("sm_nomfav", Command_GetFavorites, "Nominate from a list of your favorites");

    RegConsoleCmd("sm_mapcomment", Command_MapComment, "Comment on the current map");
    RegConsoleCmd("sm_mc", Command_MapComment, "Comment on the current map");

    RegConsoleCmd("sm_viewmap", Command_ViewMap, "View the Map Votes web page for this map");

    RegAdminCmd("sm_have_not_voted", Command_HaveNotVoted, ADMFLAG_VOTE, "Popup a vote panel to every player on the server that has not yet voted on this map");

    RegConsoleCmd("test", Test, "Test function");

    new array_size = ByteCountToCells(PLATFORM_MAX_PATH);
    g_MapList = CreateArray(array_size);
    g_MapTrie = CreateTrie();
    BuildMapListAndTrie();
}

public OnConfigsExecuted()
{
    BuildMapListAndTrie();
}

public OnAllPluginsLoaded() {
    new String:noms[PLATFORM_MAX_PATH];
    GetConVarString(g_Cvar_MapVotesNominationsName, noms, sizeof(noms));
    //g_nominations = FindPluginByFile(noms);
    g_nominations = FindPluginByFile("nominations.smx");

    //Check if nominations.smx is both available and currently running
    if(g_nominations == INVALID_HANDLE || GetPluginStatus(g_nominations) != Plugin_Running){
        SetFailState("[MapVotes] Error, nominations is currently not running");
    }
    else{
        //We should be clear to link the MapSelectMenu function
        g_Handler_MapSelectMenu = GetFunctionByName(g_nominations, "Handler_MapSelectMenu");
    }
}

public Action:Command_VoteMenu(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(!GetConVarBool(g_Cvar_MapVotesVotingEnabled))
    {
        ReplyToCommand(client, "Voting not enabled");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        CallVoteOnClient(client);
    }

    return Plugin_Handled;
}

public Action:Command_VoteUp(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(!GetConVarBool(g_Cvar_MapVotesVotingEnabled))
    {
        ReplyToCommand(client, "Voting not enabled");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        CastVote(client, 1);
    }

    return Plugin_Handled;
}

public Action:Command_VoteDown(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(!GetConVarBool(g_Cvar_MapVotesVotingEnabled))
    {
        ReplyToCommand(client, "Voting not enabled");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        CastVote(client, -1);
    }

    return Plugin_Handled;
}

public Action:Command_Favorite(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        new String:map[PLATFORM_MAX_PATH];
        if (args <= 0)
        {
            GetCurrentMap(map, sizeof(map));
            Favorite(map, client, true);
        }else{
            GetCmdArg(1, map, sizeof(map));
            MapSearch(client, map, g_MapList, FavoriteSearchHandler);
        }
    }

    return Plugin_Handled;
}
public Action:Command_Unfavorite(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        new String:map[PLATFORM_MAX_PATH];
        if (args <= 0)
        {
            GetCurrentMap(map, sizeof(map));
            Favorite(map, client, false);
        }else{
            GetCmdArg(1, map, sizeof(map));
            MapSearch(client, map, g_MapList, UnfavoriteSearchHandler);
        }

    }

    return Plugin_Handled;
}
public Action:Command_GetFavorites(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        GetFavorites(client);
    }

    return Plugin_Handled;
}

public Action:Command_ViewMap(client, args)
{
    if(client && IsClientAuthorized(client)){
        ViewMap(client);
    }

    return Plugin_Handled;
}

public Action:Command_MapComment(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if (!GetConVarBool(g_Cvar_MapVotesCommentingEnabled))
    {
        ReplyToCommand(client, "Commenting not enabled");
        return Plugin_Handled;
    }

    if (args < 1)
    {
        ReplyToCommand(client, "[MapVotes] Usage: !map_comment <comment>");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        decl String:comment[256];
        GetCmdArgString(comment, sizeof(comment));
        WriteMessage(client, comment);
    }

    return Plugin_Handled;
}

public Action:Command_HaveNotVoted(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(!GetConVarBool(g_Cvar_MapVotesVotingEnabled))
    {
        ReplyToCommand(client, "Voting not enabled");
        return Plugin_Handled;
    }

    HaveNotVoted();

    return Plugin_Handled;
}

BuildMapListAndTrie()
{
    //Build the map list
    if (ReadMapList(g_MapList,
                g_MapFileSerial,
                "nominations",
                MAPLIST_FLAG_CLEARARRAY|MAPLIST_FLAG_MAPSFOLDER)
            == INVALID_HANDLE)
    {
        if (g_MapFileSerial == -1)
        {
            SetFailState("Unable to create a valid map list.");
        }else{
            //Build the map trie; note we don't care about the value, just if the map exists in the trie
            ClearTrie(g_MapTrie);
            new String:map[PLATFORM_MAX_PATH];

            for (new i = 0; i < GetArraySize(g_MapList); i++)
            {
                GetArrayString(g_MapList, i, map, sizeof(map));
                SetTrieValue(g_MapTrie, map, 1);
            }
        }
    }
}

public SetAccessCode(&HTTPRequestHandle:request)
{
    decl String:api_key[128];
    GetConVarString(g_Cvar_MapVotesApiKey, api_key, sizeof(api_key));
    Steam_SetHTTPRequestGetOrPostParameter(request, "access_token", api_key);
}

public HTTPRequestHandle:CreateMapVotesRequest(const String:route[])
{
    decl String:base_url[256], String:url[512];
    GetConVarString(g_Cvar_MapVotesUrl, base_url, sizeof(base_url));

    //check for forward slash after base_url;
    TrimString(base_url);
    new trim_length = strlen(base_url) - 1;

    if(base_url[trim_length] == '/')
    {
        strcopy(base_url, trim_length + 1, base_url);
    }

    Format(url, sizeof(url),
            "%s%s", base_url, route);

    new HTTPRequestHandle:request = Steam_CreateHTTPRequest(HTTPMethod_POST, url);
    SetAccessCode(request);

    return request;
}

public Steam_SetHTTPRequestGetOrPostParameterInt(&HTTPRequestHandle:request, const String:param[], value)
{
    new String:tmp[64];
    IntToString(value, tmp, sizeof(tmp));
    Steam_SetHTTPRequestGetOrPostParameter(request, param, tmp);
}

public StartCooldown(client)
{
    //Ignore the server console
    if (client == 0)
        return;

    g_IsInCooldown[client] = true;
    CreateTimer(GetConVarFloat(g_Cvar_MapVotesRequestCooldownTime), RemoveCooldown, client);
}

public bool:IsClientInCooldown(client)
{
    if(client == 0)
        return false;
    else
        return g_IsInCooldown[client];
}

public Action:RemoveCooldown(Handle:timer, any:client)
{
    g_IsInCooldown[client] = false;
}

public WriteMessage(client, String:message[256])
{
    //Encode the message to be url safe
    decl String:base64[256], String:base64_url[256];
    EncodeBase64(base64, sizeof(base64), message);
    Base64MimeToUrl(base64_url, sizeof(base64_url), base64);

    decl String:uid[MAX_COMMUNITYID_LENGTH];
    Steam_GetCSteamIDForClient(client, uid, sizeof(uid));

    decl String:map[PLATFORM_MAX_PATH];
    GetCurrentMap(map, sizeof(map));

    new HTTPRequestHandle:request = CreateMapVotesRequest(WRITE_MESSAGE_ROUTE);
    Steam_SetHTTPRequestGetOrPostParameter(request, "map", map);
    Steam_SetHTTPRequestGetOrPostParameter(request, "uid", uid);
    Steam_SetHTTPRequestGetOrPostParameter(request, "comment", base64_url);
    Steam_SetHTTPRequestGetOrPostParameter(request, "base64", "1");
    Steam_SendHTTPRequest(request, ReceiveWriteMessage, GetClientUserId(client));
    StartCooldown(client);
}

public ReceiveWriteMessage(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    new client = GetClientOfUserId(userid);

    if(client && successful)
    {
        ReplyToCommand(client, "[MapVotes] Comment Added");
    }

    Steam_ReleaseHTTPRequest(request);
}

public CastVote(client, value)
{

    if(!(value == -1 || value == 0 || value == 1)){
        LogError("[MapVotes] invalid vote value %d (client: %d)", value, client);
    }else{
        decl String:map[PLATFORM_MAX_PATH];
        decl String:uid[MAX_COMMUNITYID_LENGTH];
        Steam_GetCSteamIDForClient(client, uid, sizeof(uid));

        GetCurrentMap(map, sizeof(map));

        new HTTPRequestHandle:request = CreateMapVotesRequest(CAST_VOTE_ROUTE);
        Steam_SetHTTPRequestGetOrPostParameter(request, "map", map);
        Steam_SetHTTPRequestGetOrPostParameter(request, "uid", uid);
        Steam_SetHTTPRequestGetOrPostParameterInt(request, "value", value);
        Steam_SendHTTPRequest(request, ReceiveCastVote, GetClientUserId(client));
        StartCooldown(client);
    }

}

public ReceiveCastVote(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    new client = GetClientOfUserId(userid);

    if(client && successful)
    {
        ReplyToCommand(client, "[MapVotes] Vote Cast");
    }

    Steam_ReleaseHTTPRequest(request);
}

public Favorite(String:map[PLATFORM_MAX_PATH], client, bool:favorite)
{
    decl String:uid[MAX_COMMUNITYID_LENGTH];
    Steam_GetCSteamIDForClient(client, uid, sizeof(uid));

    new HTTPRequestHandle:request;
    if(favorite)
    {
        request = CreateMapVotesRequest(FAVORITE_ROUTE);
    }else{
        request = CreateMapVotesRequest(UNFAVORITE_ROUTE);
    }

    Steam_SetHTTPRequestGetOrPostParameter(request, "map", map);
    Steam_SetHTTPRequestGetOrPostParameter(request, "uid", uid);
    Steam_SendHTTPRequest(request, ReceiveFavorite, GetClientUserId(client));
    StartCooldown(client);
}

public ReceiveFavorite(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    new client = GetClientOfUserId(userid);

    if(client && successful)
    {
        ReplyToCommand(client, "[MapVotes] Updated Favorites");
    }

    Steam_ReleaseHTTPRequest(request);
}

public MapSearch(client, String:search_key[PLATFORM_MAX_PATH], Handle:map_list, MenuHandler:handler)
{
    new String:map[PLATFORM_MAX_PATH], String:info[16];
    new Handle:menu = CreateMenu(handler, MENU_ACTIONS_DEFAULT|MenuAction_DrawItem|MenuAction_DisplayItem);
    new bool:found = false;

    for(new i=0; i<GetArraySize(map_list); i++)
    {
        GetArrayString(map_list, i, map, sizeof(map));

        //If this map matches the search key, add it to the menu
        if(StrContains(map, search_key, false) >= 0){
            AddMenuItem(menu, map, map);
            found = true;
        }
    }

    if(found)
    {
        SetMenuTitle(menu, "Found Maps");
        DisplayMenu(menu, client, MENU_TIME_FOREVER);
    }

}

public FavoriteSearchHandler(Handle:menu, MenuAction:action, param1, param2)
{
    if (action == MenuAction_End)
    {
        CloseHandle(menu);
    } else if (action == MenuAction_VoteCancel)
    {
    } else if (action == MenuAction_Select)
    {
        new client=param1;
        new String:map[PLATFORM_MAX_PATH];
        GetMenuItem(menu, param2, map, sizeof(map));
        Favorite(map, client, true);
    }
}

public UnfavoriteSearchHandler(Handle:menu, MenuAction:action, param1, param2)
{
    if (action == MenuAction_End)
    {
        CloseHandle(menu);
    } else if (action == MenuAction_VoteCancel)
    {
    } else if (action == MenuAction_Select)
    {
        new client=param1;
        new String:map[PLATFORM_MAX_PATH];
        GetMenuItem(menu, param2, map, sizeof(map));
        Favorite(map, client, false);
    }
}

public GetFavorites(client)
{
    decl String:uid[MAX_COMMUNITYID_LENGTH];
    Steam_GetCSteamIDForClient(client, uid, sizeof(uid));

    new HTTPRequestHandle:request = CreateMapVotesRequest(GET_FAVORITES_ROUTE);
    Steam_SetHTTPRequestGetOrPostParameterInt(request, "player", GetClientUserId(client));
    Steam_SetHTTPRequestGetOrPostParameter(request, "uid", uid);
    Steam_SendHTTPRequest(request, ReceiveGetFavorites, GetClientUserId(client));
    StartCooldown(client);
}

public ReceiveGetFavorites(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    new client = GetClientOfUserId(userid);
    if(false && !client)//TODO
    {
        //User logged off
        Steam_ReleaseHTTPRequest(request);
        return;
    }
    if(!successful || code != HTTPStatusCode_OK)
    {
        LogError("[MapVotes] Error at RecivedGetFavorites (HTTP Code %d; success %d)", code, successful);
        Steam_ReleaseHTTPRequest(request);
        return;
    }

    decl String:data[4096];
    Steam_GetHTTPResponseBodyData(request, data, sizeof(data));
    Steam_ReleaseHTTPRequest(request);

    new Handle:json = json_load(data);
    new Handle:maps = json_object_get(json, "maps");
    new String:map_buffer[PLATFORM_MAX_PATH];
    new junk;
    new bool:found;

    new Handle:menu = CreateMenu(NominateMapHandler, MENU_ACTIONS_DEFAULT|MenuAction_DrawItem|MenuAction_DisplayItem);

    for(new i = 0; i < json_array_size(maps); i++)
    {
        json_array_get_string(maps, i, map_buffer, sizeof(map_buffer));
        TrimString(map_buffer);
        found = GetTrieValue(g_MapTrie, map_buffer, junk);
        ReplyToCommand(client, "json[%d](%d)(%d):%s:", i, found, junk, map_buffer);//TODO
        if(found)
        {
            AddMenuItem(menu, map_buffer, map_buffer);
        }
    }

    CloseHandle(json);
    CloseHandle(maps);

    //If no maps were found don't even bother displaying a menu
    if(GetMenuItemCount(menu) > 0){
        SetMenuTitle(menu, "Favorited Maps");
        DisplayMenu(menu, client, MENU_TIME_FOREVER);
    }else{
        ReplyToCommand(client, "[MapVotes] You have no favorited maps that are on this server.");
    }
}

public NominateMapHandler(Handle:menu, MenuAction:action, param1, param2)
{

    decl result;

    // Start function call
    Call_StartFunction(g_nominations, g_Handler_MapSelectMenu);

    // Push parameters one at a time
    Call_PushCell(menu);
    Call_PushCell(action);
    Call_PushCell(param1);
    Call_PushCell(param2);

    // Finish the call, get the result
    Call_Finish(result);

    return result;
}

public CallVoteOnClient(client)
{
    new Handle:menu = CreateMenu(VoteMenuHandler);
    SetMenuTitle(menu, "Do you like this map?");
    AddMenuItem(menu, "1","Like it.");
    AddMenuItem(menu, "-1","Hate it.");
    AddMenuItem(menu, "0","I have no strong feelings one way or the other.");
    DisplayMenu(menu, client, 20);
}

public VoteMenuHandler(Handle:menu, MenuAction:action, param1, param2)
{
    if (action == MenuAction_End)
    {
        CloseHandle(menu);
    } else if (action == MenuAction_VoteCancel)
    {
    } else if (action == MenuAction_Select)
    {
        new String:info[32];
        GetMenuItem(menu, param2, info, sizeof(info));
        new value = StringToInt(info);

        CastVote(param1, value);
    }
}

public HaveNotVoted()
{
    decl String:uid[MAX_COMMUNITYID_LENGTH];
    decl String:map[PLATFORM_MAX_PATH];
    new player;
    new HTTPRequestHandle:request = CreateMapVotesRequest(HAVE_NOT_VOTED_ROUTE);

    GetCurrentMap(map, sizeof(map));
    Steam_SetHTTPRequestGetOrPostParameter(request, "map", map);

    for (new client=1; client <= MaxClients; client++)
    {
        if (!IsClientInGame(client) || IsFakeClient(client))
        {
            continue;
        }
        Steam_GetCSteamIDForClient(client, uid, sizeof(uid));
        player = GetClientUserId(client);

        Steam_SetHTTPRequestGetOrPostParameter(request, "uids", uid);
        Steam_SetHTTPRequestGetOrPostParameterInt(request, "players", player);
    }

    Steam_SendHTTPRequest(request, ReceiveHaveNotVoted, 0);
}

public ReceiveHaveNotVoted(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    if(!successful || code != HTTPStatusCode_OK)
    {
        LogError("[MapVotes] Error at RecivedHaveNotVoted (HTTP Code %d)", code);
        Steam_ReleaseHTTPRequest(request);
        return;
    }

    decl String:data[4096];
    Steam_GetHTTPResponseBodyData(request, data, sizeof(data));
    Steam_ReleaseHTTPRequest(request);

    new Handle:json = json_load(data);
    new Handle:players = json_object_get(json, "players");
    decl p;
    new String:map_buffer[PLATFORM_MAX_PATH];

    for(new i = 0; i < json_array_size(players); i++)
    {
        p = json_array_get_int(players, i);
        CallVoteOnClient(GetClientOfUserId(p));
    }
    CloseHandle(json);
    CloseHandle(players);
}

public ViewMap(client)
{
    decl String:map[PLATFORM_MAX_PATH], String:url[256], String:base_url[128];
    GetCurrentMap(map, sizeof(map));
    GetConVarString(g_Cvar_MapVotesUrl, base_url, sizeof(base_url));

    TrimString(base_url);
    new trim_length = strlen(base_url) - 1;

    if(base_url[trim_length] == '/')
    {
        strcopy(base_url, trim_length + 1, base_url);
    }

    Format(url, sizeof(url),
            "%s%s/%s", base_url, MAPS_ROUTE, map);

    ShowMOTDPanel(client, "Map Viewer", url, MOTDPANEL_TYPE_URL);

}

public Action:Test(client, args)
{
    //MapVotesCall(GET_FAVORITES_ROUTE, query_params, 0, ReceiveGetFavorites);
    new HTTPRequestHandle:request = CreateMapVotesRequest(GET_FAVORITES_ROUTE);
    Steam_SetHTTPRequestGetOrPostParameterInt(request, "player", 7);
    Steam_SetHTTPRequestGetOrPostParameter(request, "uid",  "76561197998903004");
    Steam_SendHTTPRequest(request, ReceiveGetFavorites, 0);
}

/**
 * vim: set ts=4 :
 * =============================================================================
 * map_votes
 * Interact with the Map Votes web api - https://github.com/CrimsonTautology/map_votes
 *
 * Copyright 2013 The Crimson Tautology
 * =============================================================================
 *
 */

#pragma semicolon 1

#include <sourcemod>
#include <steamtools>
#include <base64>
#include <smjansson>

#define PLUGIN_VERSION "0.1"

public Plugin:myinfo = {
    name = "MapVotes",
    author = "CrimsonTautology",
    description = "Interact with the Map Votes web api",
    version = PLUGIN_VERSION,
    url = "https://github.com/CrimsonTautology/sm_map_votes"
};

#define CAST_VOTE_ROUTE "/v1/api/cast_vote"
#define WRITE_MESSAGE_ROUTE "/v1/api/write_message"
#define FAVORITE_ROUTE "/v1/api/favorite"
#define UNFAVORITE_ROUTE "/v1/api/unfavorite"
#define GET_FAVORITES_ROUTE "/v1/api/get_favorites"
#define HAVE_NOT_VOTED_ROUTE "/v1/api/have_not_voted"
#define SERVER_QUERY_ROUTE "/v1/api/server_query"
#define MAPS_ROUTE "/maps"

#define MAX_STEAMID_LENGTH 21
#define MAX_COMMUNITYID_LENGTH 18

new Handle:g_Cvar_MapVotesUrl = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesPort = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesApiKey = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesVotingEnabled = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesCommentingEnabled = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesNominationsName = INVALID_HANDLE;
new Handle:g_Cvar_MapVotesRequestCooldownTime = INVALID_HANDLE;

new bool:g_IsInCooldown[MAXPLAYERS+1];

new g_MapFileSerial = -1;
new Handle:g_MapList = INVALID_HANDLE;
new Handle:g_MapTrie = INVALID_HANDLE;

new Handle:g_nominations = INVALID_HANDLE;
new Function:g_Handler_MapSelectMenu = INVALID_FUNCTION;

public OnPluginStart()
{

    g_Cvar_MapVotesUrl = CreateConVar("sm_map_votes_url", "", "URL to your Map Votes web page.  Remeber the \"http://\" part and to quote the entire url!");
    g_Cvar_MapVotesPort = CreateConVar("sm_map_votes_port", "80", "HTTP Port used");
    g_Cvar_MapVotesApiKey = CreateConVar("sm_map_votes_api_key", "", "The API key you generated to interact with the Map Votes web page");
    g_Cvar_MapVotesVotingEnabled = CreateConVar("sm_map_votes_voting_enabled", "1", "Whether players are allowed to vote on the current map");
    g_Cvar_MapVotesCommentingEnabled = CreateConVar("sm_map_votes_commenting_enabled", "1", "Whether players are allowed to comment on the current map");
    g_Cvar_MapVotesNominationsName = CreateConVar("sm_map_votes_nominations_plugin", "nominations.smx", "The nominations plugin used by the server");
    g_Cvar_MapVotesRequestCooldownTime = CreateConVar("sm_map_votes_request_cooldown_time", "2.0", "How long in seconds before a client can send another http request");

    RegConsoleCmd("sm_votemenu", Command_VoteMenu, "Bring up a menu to vote on the current map");
    RegConsoleCmd("sm_voteup", Command_VoteUp, "Vote that you like the current map");
    RegConsoleCmd("sm_like", Command_VoteUp, "Vote that you like the current map");
    RegConsoleCmd("sm_votedown", Command_VoteDown, "Vote that you hate the current map");
    RegConsoleCmd("sm_hate", Command_VoteDown, "Vote that you hate the current map");

    RegConsoleCmd("sm_fav", Command_Favorite, "Add this map to your favorites");
    RegConsoleCmd("sm_unfav", Command_Unfavorite, "Remove this map to your favorites");
    RegConsoleCmd("sm_nomfav", Command_GetFavorites, "Nominate from a list of your favorites");

    RegConsoleCmd("sm_mapcomment", Command_MapComment, "Comment on the current map");
    RegConsoleCmd("sm_mc", Command_MapComment, "Comment on the current map");

    RegConsoleCmd("sm_viewmap", Command_ViewMap, "View the Map Votes web page for this map");

    RegAdminCmd("sm_have_not_voted", Command_HaveNotVoted, ADMFLAG_VOTE, "Popup a vote panel to every player on the server that has not yet voted on this map");

    RegConsoleCmd("test", Test, "Test function");

    new array_size = ByteCountToCells(PLATFORM_MAX_PATH);
    g_MapList = CreateArray(array_size);
    g_MapTrie = CreateTrie();
}

public OnConfigsExecuted()
{
    BuildMapListAndTrie();
}

public OnAllPluginsLoaded() {
    new String:noms[PLATFORM_MAX_PATH];
    GetConVarString(g_Cvar_MapVotesNominationsName, noms, sizeof(noms));
    //g_nominations = FindPluginByFile(noms);
    g_nominations = FindPluginByFile("nominations.smx");

    //Check if nominations.smx is both available and currently running
    if(g_nominations == INVALID_HANDLE || GetPluginStatus(g_nominations) != Plugin_Running){
        SetFailState("[MapVotes] Error, nominations is currently not running");
    }
    else{
        //We should be clear to link the MapSelectMenu function
        g_Handler_MapSelectMenu = GetFunctionByName(g_nominations, "Handler_MapSelectMenu");
    }
}

public Action:Command_VoteMenu(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(!GetConVarBool(g_Cvar_MapVotesVotingEnabled))
    {
        ReplyToCommand(client, "Voting not enabled");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        CallVoteOnClient(client);
    }

    return Plugin_Handled;
}

public Action:Command_VoteUp(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(!GetConVarBool(g_Cvar_MapVotesVotingEnabled))
    {
        ReplyToCommand(client, "Voting not enabled");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        CastVote(client, 1);
    }

    return Plugin_Handled;
}

public Action:Command_VoteDown(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(!GetConVarBool(g_Cvar_MapVotesVotingEnabled))
    {
        ReplyToCommand(client, "Voting not enabled");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        CastVote(client, -1);
    }

    return Plugin_Handled;
}

public Action:Command_Favorite(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        new String:map[PLATFORM_MAX_PATH];
        if (args <= 0)
        {
            GetCurrentMap(map, sizeof(map));
            Favorite(map, client, true);
        }else{
            GetCmdArg(1, map, sizeof(map));
            MapSearch(client, map, g_MapList, FavoriteSearchHandler);
        }
    }

    return Plugin_Handled;
}
public Action:Command_Unfavorite(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        new String:map[PLATFORM_MAX_PATH];
        if (args <= 0)
        {
            GetCurrentMap(map, sizeof(map));
            Favorite(map, client, false);
        }else{
            GetCmdArg(1, map, sizeof(map));
            MapSearch(client, map, g_MapList, UnfavoriteSearchHandler);
        }

    }

    return Plugin_Handled;
}
public Action:Command_GetFavorites(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        GetFavorites(client);
    }

    return Plugin_Handled;
}

public Action:Command_ViewMap(client, args)
{
    if(client && IsClientAuthorized(client)){
        ViewMap(client);
    }

    return Plugin_Handled;
}

public Action:Command_MapComment(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if (!GetConVarBool(g_Cvar_MapVotesCommentingEnabled))
    {
        ReplyToCommand(client, "Commenting not enabled");
        return Plugin_Handled;
    }

    if (args < 1)
    {
        ReplyToCommand(client, "[MapVotes] Usage: !map_comment <comment>");
        return Plugin_Handled;
    }

    if(client && IsClientAuthorized(client)){
        decl String:comment[256];
        GetCmdArgString(comment, sizeof(comment));
        WriteMessage(client, comment);
    }

    return Plugin_Handled;
}

public Action:Command_HaveNotVoted(client, args)
{
    if(IsClientInCooldown(client))
    {
        ReplyToCommand(client, "User in cooldown");
        return Plugin_Handled;
    }

    if(!GetConVarBool(g_Cvar_MapVotesVotingEnabled))
    {
        ReplyToCommand(client, "Voting not enabled");
        return Plugin_Handled;
    }

    HaveNotVoted();

    return Plugin_Handled;
}

BuildMapListAndTrie()
{
    //Build the map list
    if (ReadMapList(g_MapList,
                g_MapFileSerial,
                "nominations",
                MAPLIST_FLAG_CLEARARRAY|MAPLIST_FLAG_MAPSFOLDER)
            == INVALID_HANDLE)
    {
        if (g_MapFileSerial == -1)
        {
            SetFailState("Unable to create a valid map list.");
        }else{
            //Build the map trie; note we don't care about the value, just if the map exists in the trie
            ClearTrie(g_MapTrie);
            new String:map[PLATFORM_MAX_PATH];

            for (new i = 0; i < GetArraySize(g_MapList); i++)
            {
                GetArrayString(g_MapList, i, map, sizeof(map));
                SetTrieValue(g_MapTrie, map, 1);
            }
        }
    }
}

public SetAccessCode(&HTTPRequestHandle:request)
{
    decl String:api_key[128];
    GetConVarString(g_Cvar_MapVotesApiKey, api_key, sizeof(api_key));
    Steam_SetHTTPRequestGetOrPostParameter(request, "access_token", api_key);
}

public HTTPRequestHandle:CreateMapVotesRequest(const String:route[])
{
    decl String:base_url[256], String:url[512];
    GetConVarString(g_Cvar_MapVotesUrl, base_url, sizeof(base_url));

    //check for forward slash after base_url;
    TrimString(base_url);
    new trim_length = strlen(base_url) - 1;

    if(base_url[trim_length] == '/')
    {
        strcopy(base_url, trim_length + 1, base_url);
    }

    Format(url, sizeof(url),
            "%s%s", base_url, route);

    new HTTPRequestHandle:request = Steam_CreateHTTPRequest(HTTPMethod_POST, url);
    SetAccessCode(request);

    return request;
}

public Steam_SetHTTPRequestGetOrPostParameterInt(&HTTPRequestHandle:request, const String:param[], value)
{
    new String:tmp[64];
    IntToString(value, tmp, sizeof(tmp));
    Steam_SetHTTPRequestGetOrPostParameter(request, param, tmp);
}

public StartCooldown(client)
{
    //Ignore the server console
    if (client == 0)
        return;

    g_IsInCooldown[client] = true;
    CreateTimer(GetConVarFloat(g_Cvar_MapVotesRequestCooldownTime), RemoveCooldown, client);
}

public bool:IsClientInCooldown(client)
{
    if(client == 0)
        return false;
    else
        return g_IsInCooldown[client];
}

public Action:RemoveCooldown(Handle:timer, any:client)
{
    g_IsInCooldown[client] = false;
}

public WriteMessage(client, String:message[256])
{
    //Encode the message to be url safe
    decl String:base64[256], String:base64_url[256];
    EncodeBase64(base64, sizeof(base64), message);
    Base64MimeToUrl(base64_url, sizeof(base64_url), base64);

    decl String:uid[MAX_COMMUNITYID_LENGTH];
    Steam_GetCSteamIDForClient(client, uid, sizeof(uid));

    decl String:map[PLATFORM_MAX_PATH];
    GetCurrentMap(map, sizeof(map));

    new HTTPRequestHandle:request = CreateMapVotesRequest(WRITE_MESSAGE_ROUTE);
    Steam_SetHTTPRequestGetOrPostParameter(request, "map", map);
    Steam_SetHTTPRequestGetOrPostParameter(request, "uid", uid);
    Steam_SetHTTPRequestGetOrPostParameter(request, "comment", base64_url);
    Steam_SetHTTPRequestGetOrPostParameter(request, "base64", "1");
    Steam_SendHTTPRequest(request, ReceiveWriteMessage, GetClientUserId(client));
    StartCooldown(client);
}

public ReceiveWriteMessage(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    new client = GetClientOfUserId(userid);

    if(client && successful)
    {
        ReplyToCommand(client, "[MapVotes] Comment Added");
    }

    Steam_ReleaseHTTPRequest(request);
}

public CastVote(client, value)
{

    if(!(value == -1 || value == 0 || value == 1)){
        LogError("[MapVotes] invalid vote value %d (client: %d)", value, client);
    }else{
        decl String:map[PLATFORM_MAX_PATH];
        decl String:uid[MAX_COMMUNITYID_LENGTH];
        Steam_GetCSteamIDForClient(client, uid, sizeof(uid));

        GetCurrentMap(map, sizeof(map));

        new HTTPRequestHandle:request = CreateMapVotesRequest(CAST_VOTE_ROUTE);
        Steam_SetHTTPRequestGetOrPostParameter(request, "map", map);
        Steam_SetHTTPRequestGetOrPostParameter(request, "uid", uid);
        Steam_SetHTTPRequestGetOrPostParameterInt(request, "value", value);
        Steam_SendHTTPRequest(request, ReceiveCastVote, GetClientUserId(client));
        StartCooldown(client);
    }

}

public ReceiveCastVote(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    new client = GetClientOfUserId(userid);

    if(client && successful)
    {
        ReplyToCommand(client, "[MapVotes] Vote Cast");
    }

    Steam_ReleaseHTTPRequest(request);
}

public Favorite(String:map[PLATFORM_MAX_PATH], client, bool:favorite)
{
    decl String:uid[MAX_COMMUNITYID_LENGTH];
    Steam_GetCSteamIDForClient(client, uid, sizeof(uid));

    new HTTPRequestHandle:request;
    if(favorite)
    {
        request = CreateMapVotesRequest(FAVORITE_ROUTE);
    }else{
        request = CreateMapVotesRequest(UNFAVORITE_ROUTE);
    }

    Steam_SetHTTPRequestGetOrPostParameter(request, "map", map);
    Steam_SetHTTPRequestGetOrPostParameter(request, "uid", uid);
    Steam_SendHTTPRequest(request, ReceiveFavorite, GetClientUserId(client));
    StartCooldown(client);
}

public ReceiveFavorite(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    new client = GetClientOfUserId(userid);

    if(client && successful)
    {
        ReplyToCommand(client, "[MapVotes] Updated Favorites");
    }

    Steam_ReleaseHTTPRequest(request);
}

public MapSearch(client, String:search_key[PLATFORM_MAX_PATH], Handle:map_list, MenuHandler:handler)
{
    new String:map[PLATFORM_MAX_PATH], String:info[16];
    new Handle:menu = CreateMenu(handler, MENU_ACTIONS_DEFAULT|MenuAction_DrawItem|MenuAction_DisplayItem);
    new bool:found = false;

    for(new i=0; i<GetArraySize(map_list); i++)
    {
        GetArrayString(map_list, i, map, sizeof(map));

        //If this map matches the search key, add it to the menu
        if(StrContains(map, search_key, false) >= 0){
            AddMenuItem(menu, map, map);
            found = true;
        }
    }

    if(found)
    {
        SetMenuTitle(menu, "Found Maps");
        DisplayMenu(menu, client, MENU_TIME_FOREVER);
    }

}

public FavoriteSearchHandler(Handle:menu, MenuAction:action, param1, param2)
{
    if (action == MenuAction_End)
    {
        CloseHandle(menu);
    } else if (action == MenuAction_VoteCancel)
    {
    } else if (action == MenuAction_Select)
    {
        new client=param1;
        new String:map[PLATFORM_MAX_PATH];
        GetMenuItem(menu, param2, map, sizeof(map));
        Favorite(map, client, true);
    }
}

public UnfavoriteSearchHandler(Handle:menu, MenuAction:action, param1, param2)
{
    if (action == MenuAction_End)
    {
        CloseHandle(menu);
    } else if (action == MenuAction_VoteCancel)
    {
    } else if (action == MenuAction_Select)
    {
        new client=param1;
        new String:map[PLATFORM_MAX_PATH];
        GetMenuItem(menu, param2, map, sizeof(map));
        Favorite(map, client, false);
    }
}

public GetFavorites(client)
{
    decl String:uid[MAX_COMMUNITYID_LENGTH];
    Steam_GetCSteamIDForClient(client, uid, sizeof(uid));

    new HTTPRequestHandle:request = CreateMapVotesRequest(GET_FAVORITES_ROUTE);
    Steam_SetHTTPRequestGetOrPostParameterInt(request, "player", GetClientUserId(client));
    Steam_SetHTTPRequestGetOrPostParameter(request, "uid", uid);
    Steam_SendHTTPRequest(request, ReceiveGetFavorites, GetClientUserId(client));
    StartCooldown(client);
}

public ReceiveGetFavorites(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    new client = GetClientOfUserId(userid);
    if(false && !client)//TODO
    {
        //User logged off
        Steam_ReleaseHTTPRequest(request);
        return;
    }
    if(!successful || code != HTTPStatusCode_OK)
    {
        LogError("[MapVotes] Error at RecivedGetFavorites (HTTP Code %d; success %d)", code, successful);
        Steam_ReleaseHTTPRequest(request);
        return;
    }

    decl String:data[4096];
    Steam_GetHTTPResponseBodyData(request, data, sizeof(data));
    Steam_ReleaseHTTPRequest(request);

    new Handle:json = json_load(data);
    new Handle:maps = json_object_get(json, "maps");
    new String:map_buffer[PLATFORM_MAX_PATH];
    new junk;

    new Handle:menu = CreateMenu(NominateMapHandler);

    for(new i = 0; i < json_array_size(maps); i++)
    {
        json_array_get_string(maps, i, map_buffer, sizeof(map_buffer));
        if(GetTrieValue(g_MapTrie, map_buffer, junk))
        {
            AddMenuItem(menu, map_buffer, map_buffer);
            ReplyToCommand(client, "%s", map_buffer);//TODO
        }
    }

    CloseHandle(json);
    CloseHandle(maps);

    //If no maps were found don't even bother displaying a menu
    if(GetMenuItemCount(menu) > 0){
        SetMenuTitle(menu, "Favorited Maps");
        DisplayMenu(menu, client, MENU_TIME_FOREVER);
    }else{
        ReplyToCommand(client, "[MapVotes] You have no favorited maps that are on this server.");
    }
}

public NominateMapHandler(Handle:menu, MenuAction:action, param1, param2)
{

    decl result;

    // Start function call
    Call_StartFunction(g_nominations, g_Handler_MapSelectMenu);

    // Push parameters one at a time
    Call_PushCell(menu);
    Call_PushCell(action);
    Call_PushCell(param1);
    Call_PushCell(param2);

    // Finish the call, get the result
    Call_Finish(result);

    return result;
}

public CallVoteOnClient(client)
{
    new Handle:menu = CreateMenu(VoteMenuHandler);
    SetMenuTitle(menu, "Do you like this map?");
    AddMenuItem(menu, "1","Like it.");
    AddMenuItem(menu, "-1","Hate it.");
    AddMenuItem(menu, "0","I have no strong feelings one way or the other.");
    DisplayMenu(menu, client, 20);
}

public VoteMenuHandler(Handle:menu, MenuAction:action, param1, param2)
{
    if (action == MenuAction_End)
    {
        CloseHandle(menu);
    } else if (action == MenuAction_VoteCancel)
    {
    } else if (action == MenuAction_Select)
    {
        new String:info[32];
        GetMenuItem(menu, param2, info, sizeof(info));
        new value = StringToInt(info);

        CastVote(param1, value);
    }
}

public HaveNotVoted()
{
    decl String:uid[MAX_COMMUNITYID_LENGTH];
    decl String:map[PLATFORM_MAX_PATH];
    new player;
    new HTTPRequestHandle:request = CreateMapVotesRequest(HAVE_NOT_VOTED_ROUTE);

    GetCurrentMap(map, sizeof(map));
    Steam_SetHTTPRequestGetOrPostParameter(request, "map", map);

    for (new client=1; client <= MaxClients; client++)
    {
        if (!IsClientInGame(client) || IsFakeClient(client))
        {
            continue;
        }
        Steam_GetCSteamIDForClient(client, uid, sizeof(uid));
        player = GetClientUserId(client);

        Steam_SetHTTPRequestGetOrPostParameter(request, "uids", uid);
        Steam_SetHTTPRequestGetOrPostParameterInt(request, "players", player);
    }

    Steam_SendHTTPRequest(request, ReceiveHaveNotVoted, 0);
}

public ReceiveHaveNotVoted(HTTPRequestHandle:request, bool:successful, HTTPStatusCode:code, any:userid)
{
    if(!successful || code != HTTPStatusCode_OK)
    {
        LogError("[MapVotes] Error at RecivedHaveNotVoted (HTTP Code %d)", code);
        Steam_ReleaseHTTPRequest(request);
        return;
    }

    decl String:data[4096];
    Steam_GetHTTPResponseBodyData(request, data, sizeof(data));
    Steam_ReleaseHTTPRequest(request);

    new Handle:json = json_load(data);
    new Handle:players = json_object_get(json, "players");
    decl p;
    new String:map_buffer[PLATFORM_MAX_PATH];

    for(new i = 0; i < json_array_size(players); i++)
    {
        p = json_array_get_int(players, i);
        CallVoteOnClient(GetClientOfUserId(p));
    }
    CloseHandle(json);
    CloseHandle(players);
}

public ViewMap(client)
{
    decl String:map[PLATFORM_MAX_PATH], String:url[256], String:base_url[128];
    GetCurrentMap(map, sizeof(map));
    GetConVarString(g_Cvar_MapVotesUrl, base_url, sizeof(base_url));

    TrimString(base_url);
    new trim_length = strlen(base_url) - 1;

    if(base_url[trim_length] == '/')
    {
        strcopy(base_url, trim_length + 1, base_url);
    }

    Format(url, sizeof(url),
            "%s%s/%s", base_url, MAPS_ROUTE, map);

    ShowMOTDPanel(client, "Map Viewer", url, MOTDPANEL_TYPE_URL);

}

public Action:Test(client, args)
{
    //MapVotesCall(GET_FAVORITES_ROUTE, query_params, 0, ReceiveGetFavorites);
    new HTTPRequestHandle:request = CreateMapVotesRequest(GET_FAVORITES_ROUTE);
    Steam_SetHTTPRequestGetOrPostParameterInt(request, "player", 7);
    Steam_SetHTTPRequestGetOrPostParameter(request, "uid",  "76561197998903004");
    Steam_SendHTTPRequest(request, ReceiveGetFavorites, 0);
}