package Xchat::XPI::Events;

use strict;
use warnings;

use Xchat qw/:all/;

use lib get_info 'xchatdir';
use Xchat::XPI;

use constant {
 DEFAULT_DELAY => 1000
};

our $VERSION = '0.04';

sub delay {
 my $d = shift;
 $d = (defined $d) ? int $d : DEFAULT_DELAY;
 return hook_timer $d, sub {
  my ($cb, $data) = @{$_[0]};
  &$cb($data);
  return REMOVE;
 }, { data => \@_ };
}

my %reorder;

sub filter {
 return unless @_ == 3;
 not defined and return for @_;
 my ($cb, $to) = @_[1, 2];
 return hook_print $_[0], sub {
  my @args = @{$_[0]};
  if ($cb->(@args)) {
   $reorder{$to}->(@args) if exists $reorder{$to};
   emit_print $to, @args;
   return EAT_ALL;
  } else {
   return EAT_NONE;
  }
 }
}

use base qw/Exporter/;

our @EXPORT         = ();
our %EXPORT_TAGS    = (
 'funcs'  => [ qw/delay filter/ ],
 'consts' => [ qw/DEFAULT_DELAY/ ]
);
our @EXPORT_OK      = map { @$_ } values %EXPORT_TAGS;
$EXPORT_TAGS{'all'} = [ @EXPORT_OK ];

1;
