# We define our plugin class
package WakeUp;

# We use strict Perl syntax for cleaner code
use strict;

# We use the SPADS plugin API module
use SpadsPluginApi;

use Data::Dumper;

# We don't want warnings when the plugin is reloaded
no warnings 'redefine';

# This is the first version of the plugin
my $pluginVersion='0.1';

# This plugin is compatible with any SPADS version which supports plugins
# (only SPADS versions >= 0.11.5 support plugins)
my $requiredSpadsVersion='0.11.5';

# We define 2 global settings (mandatory for plugins implementing new commands):
# - commandsFile: name of the plugin commands rights configuration file (located in etc dir, same syntax as commands.conf)
# - helpFile: name of plugin commands help file (located in plugin dir, same syntax as help.dat)
my %globalPluginParams = ( MinWakeUpDelay => ['integer','integerRange'],
                           commandsFile => ['notNull'],
                           helpFile => ['notNull'] );
# my %presetPluginParams;




# set lastWokeUp 60min. into the past
my $lastWokeUp = time - 3600;

# This is how SPADS gets our version number (mandatory callback)
sub getVersion { return $pluginVersion; }

# This is how SPADS determines if the plugin is compatible (mandatory callback)
sub getRequiredSpadsVersion { return $requiredSpadsVersion; }

# This is how SPADS finds what settings we need in our configuration file (mandatory callback for configurable plugins)
sub getParams { return [\%globalPluginParams,{}]; }



# This is our constructor, called when the plugin is loaded by SPADS (mandatory callback)
sub new {

  # Constructors take the class name as first parameter
  my $class=shift;

  # We create a hash which will contain the plugin data
  my $self = {};

  # We instanciate this hash as an object of the given class
  bless($self,$class);

  # We declare our new command and the associated handler
  addSpadsCommandHandler({wakeup => \&hWakeup});

  # We call the API function "slog" to log a notice message (level 3) when the plugin is loaded
  slog("Plugin loaded (version $pluginVersion)",3);

  # We return the instantiated plugin
  return $self;

}

# This is the callback called when the plugin is unloaded
sub onUnload {

  # We remove our new command handler
  removeSpadsCommandHandler(['wakeup']);

  # We log a notice message when the plugin is unloaded
  slog("Plugin unloaded",3);

}

sub hWakeup {
  my ($source,$user,$p_params,$checkOnly)=@_;

  my $p_conf=getPluginConf();

  my $autohost=getSpringInterface();
  my $ahState=$autohost->getState();

  my $lobby = getLobbyInterface();
  my $lobbyState = getLobbyState();

  # my $runningBattle = getRunningBattle();
  #print Dumper($autohost);
  #print Dumper($ahState);
  #print Dumper($lobby);
  #print Dumper($lobbyState);
  # $Data::Dumper::Maxdepth = 2;
  #print Dumper(getSpadsConfFull()->{users});
  
  if($#{$p_params} != -1) {
    invalidSyntax($user,"ring");
    return 0;
  }


  
  if($lobbyState < 6 || ! %{$lobby->{battle}}) {
    answer("Unable to ring, battle is closed");
    return 0;
  }

  if(time < ($lastWokeUp + $p_conf->{MinWakeUpDelay})) {
    answer("Unable to Wake Up, Wait at least ".( ($lastWokeUp + $p_conf->{MinWakeUpDelay}) - time)." more seconds.");
    return 0;
  }

  my @rungUsers;
  my @playerList;
  my @specList;
  my @alreadyRungUsers;
  my $ringType='unready/unsynced player';

  my $p_bUsers=$lobby->{battle}->{users};
  
  print "autohost->State: ".$autohost->getState()."\n";
  if($autohost->getState() == 0) {
    foreach my $user (keys %{$lobby->{battle}->{users}}) {  
      if(defined $lobby->{battle}->{users}->{$user}->{battleStatus} && ! $lobby->{battle}->{users}->{$user}->{battleStatus}->{mode} && $user ne $lobby->{battle}->{founder}) {
          push(@specList,$user);
      }
    }
  }

  if(@specList) {
    return 1 if($checkOnly);
    
    my $rungUsersString=join(",",@specList);
    my $ringMsg;
    if(length($rungUsersString) > 50) {
      $ringMsg="Ringing ".($#specList+1)."Specs";
    }else{
      $ringMsg="Ringing Spec(s): $rungUsersString";
    }
    sayBattleAndGame("$ringMsg (by $user)");
    foreach my $rungUser (@specList) {
      # $lastRungUsers{$rungUser}=time;
      queueLobbyCommand(["RING",$rungUser]);
    }
    $lastWokeUp = time;
  } else {
    answer("There is no one to ring");
  }
}

1;
