print "${BGreen}Loading event.pl\n";
%Events = ();
%EventList = ();


sub cmd_event {
    my ($What,$Seconds,$count);


    if (/^(\d+)$/) {
      $count = 0;
      # Remove a certain highlight
      foreach (keys %Events) {
	if (++$count == $1) {
	  print "Deleted: $_ ($Events{$_} seconds)\n";
	  delete $Events{$_};
	  delete $EventList{$_};
	  return;
	}
      }
      print "No such event (there are only $count!) - type event to see a list.\n";
    } elsif (/^(\d+)\s+(.*)/) { # Display highlights
        $Seconds = $1; 
	$What = $2;
        $Events{$What} = $Seconds;
	$EventList{$What} = $Seconds;
        print "Every ${Seconds} seconds I will send: ${What}\n" unless $Loading;    
    } else {
        print "Following events are active:\n";
	print "${BWhite}##${BRed}--${BWhite}Seconds${BRed}--${BWhite}Command${BRed}-------------------------------${White}\n";
        foreach (keys %Events) {
            printf "${BWhite}%2d) ${BRed}%7d  ${Red}$_\n", ++$count, $Events{$_};
        }
        print "${White}\nUse event <seconds> <string> to add an event.\n";
        print "Use event <number> to remove.\n";
    }
}

sub save_events {
    local (*FH) = $_[0];
    foreach (keys %Events) {
        print FH "event ", $Events{$_}, " $_\n";
    }
}

sub check_events {
  foreach (keys %EventList) {
    $EventList{$_} -= 1;
    if (!$EventList{$_}) {
      run($_);
      $EventList{$_} = $Events{$_};
    }
  }
}

sub make_event {
  my $time  = shift;
  my $event = shift;
  
  $Events{$event} = $time;
  $EventList{$event} = $time;
}

sub delete_event {
  my $event = shift;

  delete $Events{$event};
  delete $EventList{$event};   
}

save_add(\&save_events);
load_add("event", \&cmd_event);
callout_add(\&check_events, 1);
