=head1 NAME

Wala::Editor - generate a wiki page editor

=head1 SYNOPSIS

    use Wala::Editor;
    my $wikitext = new Wala::Editor;

=head1 DESCRIPTION

=cut

package Wala::Editor;

use strict;
use warnings;
no  warnings 'uninitialized';

use Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK;


sub new {
  my $class = shift;
  my (%conf) = @_;

  my $self = { };
  
  if (defined $class) {
    bless $self, $class;
  } else {
    bless $self;
  }

  # Deal with any options we may've gotten.
  if (%conf) { $self->conf(%conf); }

  return $self;

}


# Configure the editor.
sub conf {
  my $self = shift;
  my (%conf) = @_;

  my %table = (
    file_text => sub { $self->file_text($_[0]) },
  );

  # Handle keys of conf hash - some may need to be set via a method.
  for my $key (keys %conf) {

    if (exists $table{$key}) {
      $table{$key}->($conf{$key});
    } else {
      $self->{$key} = $conf{$key};
    }

  }

}


# Get or set the page name
sub page {
  my $self = shift;

  if (defined $_[0]) {
    $self->{'page'} = $_[0];
  }

  return $self->{'page'};

}


# Get or set the text of the page
sub file_text {
  my $self = shift;
  my ($file_text) = @_;

  if (defined $file_text) {
    $file_text =~ s/</&lt;/g;
    $file_text =~ s/>/&gt;/g;

    $self->{'file_text'} = $file_text;
    return;
  } else { 
    return $self->{'file_text'};
  }

}


sub render {
    my $self = shift;

    my $timestamp = time;

    my $result = <<END_HTML;
<form action="$self->{scriptname}" method="post">
  <fieldset style="width: 95%; height: 80%; margin-left: auto; margin-right: auto;">
    <input type="hidden" name="id" value="$self->{page}" />
    <input type="hidden" name="action" value="post" />
    <input type="hidden" name="timestamp" value="$timestamp" />
    <textarea name="filetext" rows="40" cols="80"
     style="width: 100%; height: 80%; clear: both;">$self->{file_text}</textarea>
  </fieldset>

  <table border="0">
    <tr>
      <td>Summary:</td> <td><input type="text" name="summary" size="30" /></td>
      <td>$self->{message}</td>
    </tr>
    <tr>
      <td></td>
      <td><input type="submit" value="Save" />
END_HTML

    if ($self->{'username'}) {
        $result .= "You are logged in as " . $self->{'username'} . ".";
    } else {
        $result .= "You are not logged in.";
    }

    $result .= "</td></tr>\n</table></form>\n";

    return $result;

}

1;

