=head1 NAME

CCL::Undo - Create and handle change lists

=head1 DESCRIPTION

This package is used by the current CCL API to handle change lists.

=cut

package CCL::Undo;

use strict;

=head2 CONSTRUCTORS

=head3 new

This is mostly used internally.

It might take a parameter with the CCL API which it references.  Not
sure if that's necessary.

=cut

sub new {
  my $this=shift;
  my $class=ref($this) || $this;
  my $self={
            changes => [],
           };
  bless $self, $class;

  $self;
}

=head2 REGISTERING CHANGES

=head3 change

This is the reciever for the change signal, see
C<CclDatabase::signalChange>.  Arguments therefore are

  $cl->change($path, $type, $new, $old);

=cut

sub change {
  my $self=shift;

  push @{$self->{changes}}, [@_];

  1;
}

=head2 UNDOING CHANGES

=head3 undo

  $undohandler->undo($api);

Applies the current undo list, and leaving a blank slate.

=cut

sub undo {
  my $self=shift;
  my $api=shift;

  my $rv;

  # performing the operations here will create more undo info, we
  # mustn't get confused!
  my $changes=$self->{changes};
  $self->{changes} = [];

  for my $change (reverse @$changes) {
    $rv = $self->undoChange($api, @$change);
    if ($rv) {
      return $rv;
    }
  }

  undef;
}

=head3 undoChange

I<internal>

Undoes an individual change.

=cut

sub undoChange {
  my $self=shift;
  my $api=shift;

  my $path=shift;
  my $type=shift;
  # note re-ordering of old and new!
  my $old=shift;
  my $new=shift;

  if ($type == 0) {
    # parameter change
    if (defined $new && defined $old) {
      # parameter value change
      $api->setStringValue($path, $new);
    } elsif (defined $new) {
      # parameter deletion, so we need to recreate it
      $api->createParam($path, $new);
    } else {
      # parameter creation, so we need to delete it
      $api->deleteParam($path);
    }
  } elsif ($type == 1) {
    # object creation, so we need to delete an object
    $api->deleteObj($path);
  } elsif ($type == 2) {
    # object deletion, so we need to create an object
  } else {
    return "Unknown change type $type";
  }

  undef;
}

=head2 OTHER API ACCESS

=head3 clearList

Clears the current undo list.

=cut

sub clearList {
  my $self=shift;
  $self->{changes} = [];
}

1;
