package MObject;

use strict;
use vars qw(%Elements);

%Elements = (
  'fg' => sub {
    my ($self, $target) = @_;
    my $r = int(($self->container->{en_fire} || 0) / 2);
    $self->{en_fire} += $r;
    $self->container->{en_fire} -= $r;
  },
  'wg' => sub {
    my ($self, $target) = @_;
    my $r = int(($self->container->{en_water} || 0) / 3);
    $self->{en_water} += $r;
    $self->container->{en_water} -= $r;
  },
  'ag' => sub {
    my ($self, $target) = @_;
    my $r = int(($self->container->{en_air} || 0) / 4);
    $self->{en_air} += $r;
    $self->container->{en_air} -= $r;
  },
  'eg' => sub {
    my ($self, $target) = @_;
    my $r = int(($self->container->{en_earth} || 0) / 5);
    $self->{en_earth} += $r;
    $self->container->{en_earth} -= $r;
  },

  'fm' => sub {
    my ($self, $target) = @_;
    $self->{en_fire} += $self->{en_air} * $self->{en_earth} / 2;
    $self->{en_air} = $self->{en_earth} = 0;
  },

  'ec' => sub {
    my ($self, $target) = @_;
    if ($self->en_earth >= 3) {
      $self->{en_earth} -= 3;
      $self->_m_docreate('/core/waybread');
    } else {
      $self->{en_earth} = 0;
      $self->_m_docreate('/core/gooey');
    }
  },
  'et' => sub {
    my ($self, $target) = @_;
    return unless $target and $target->vistype;
    if ($self->en_earth >= ($target->weight / 4)) {
      $self->{en_earth} -= ($target->weight / 4);
      $self->act("You point at @{[$target->name]} and $GENDER_NOM[$target->gender] is swallowed up by the earth!",
                 "@{[$self->name]} points at @{[$target->name]} and $GENDER_NOM[$target->gender] vanishes into a hole in the ground.",
                 "@{[$self->name]} points at you and the ground opens up beneath your feet!",
                 $target);
      $target->dispose;
    } else {
      $self->{en_earth} /= 2;
      $target->send("You feel a slight rumbling under your feet.");
    }
  },
);

sub _m_docreate {
  my ($self, $proto) = @_;

  $self->add_contents(my $obj = new MObject('prototype' => $proto));
  $self->act("You create @{[$obj->name]}.",
                        "@{[$self->name]} creates @{[$obj->name]}.");
}

sub cast {
  my ($self, $spell, $target, $opts) = @_;

  $target = $self->get_vis_object($target) if $target;

  return "there was an odd number of characters"
    if length($spell) % 2;

  my @elem;
  push @elem, (reverse (chop $spell) . (chop $spell)) while $spell;

  $self->send(join '-', @elem);

  foreach (@elem) {
    &{$Elements{$_} || sub {}}($self, $target);
  }

  return 0;  
}

1;
