package MEvent;
use strict;

use MCoreTools;
use MScheduler;

my %param_include = map {$_, 1} qw(name owner time reschedule no_catch_up no_store);

sub new {
  my ($class, %param) = @_;

  if ($param{owner}) {
    if (!ref $param{owner}) {
      croak "$class: can't have non-object owner";
    } elsif ($param{owner}->isa('MObject')) {
      $param{owner} = $param{owner}->as_ref;
    } elsif (!$param{owner}->isa('MObjectRef') and !$param{no_store}) {
      carp "$class being created with non-world object as owner and not no_store";
      $param{no_store} = 1;
    }
  }
 
  if (!$param{is_real_time}) {
    $param{'time'} /= $::Config{time_scale} if $param{'time'};
    $param{reschedule} /= $::Config{time_scale} if $param{reschedule};
  }
  
  $param{time} += MScheduler->realclock() unless $param{absolute};

  return bless {
    name => $param{name} || '',
    (map {$_, $param{$_}} grep $param_include{$_}, keys %param),
  }, $class;
}
sub schedule {
  #mudlog "DEBUG: scheduling ". ($_[0]{name} || 'undef') ." time ". ($_[0]{time} - MScheduler->realclock());
  MScheduler->add_event($_[0]); $_[0];
} 
sub run {
  my ($self) = @_;
  if ($self->{reschedule}) {
    $self->{time} =
      ($self->{no_catch_up} ? MScheduler->realclock : $self->{time})
      + $self->{reschedule};
    MScheduler->add_event($self);
  }
}
sub abort {}
sub clone {return MFreezer::clone($_[0])}
sub cloneForNow {my $o = MFreezer::clone($_[0]); $o->{time} = MScheduler->realclock(); $o}

sub owner {$_[0]{owner}}
sub name {$_[0]{name}}
sub time {$_[0]{'time'} || 0}
sub reschedule {$_[0]{reschedule}}
sub no_catch_up {$_[0]{no_catch_up}}
sub no_store {$_[0]{'no_store'} || 0}
