package MTransaction;
use strict;

use MCoreTools;
use MScheduler;
use MInitializable;

use vars qw(@ISA @Stack);

@ISA = qw(MInitializable);

=head1 Notes on Transactions

As mpMUD is not currently threaded, we don't need a full transaction
system. In particular, comparisons are not necessary.

However, being able to not commit changes is useful in case an event fails.

=head2 Current subset of transaction behavior:

There will be a 'stack' of transactions. Each one holds 'context info' - in
particular, for events caused by user input, it holds the connection and user
objects.

=head1 Methods

=over 4

=item open(I<CONTEXT...>)

The open method creates a transaction and places it on the stack. C<CONTEXT> are key-value
pairs which can be accessed later.

=cut

sub open {
  my ($class, %context) = @_;

  my $self = bless {
    nested => 0,
    context => \%context,
    # changes => {},
  }, $class;
  push @Stack, $self;
  return $self;
}

=item openNested(I<CONTEXT...>)



=cut

sub openNested {my $self = shift()->open(@_); $self->{nested} = 1; $self}

sub close {
  my ($self) = @_;
  
  while ($Stack[-1] and $Stack[-1] != $self) {
    mudlog "DEBUG: transaction: closing inner transaction ".$Stack[-1]->name;
    $Stack[-1]->close;
  }
  pop @Stack;
}

sub commit {}

sub getContextItem {
  my $self;
  ref($self = $_[0]) or ($self = $Stack[-1]) or croak "No current transaction available";
  return $self->{context}{$_[1]}
}

sub name {"$_[0]"}

1;

