
package HTML::WebMake::CGI::Edit;

use strict;
use HTML::WebMake::CGI::CGIBase;
use HTML::WebMake::CGI::Site;

use vars	qw{
  	@ISA
};

@ISA = qw(HTML::WebMake::CGI::CGIBase);

###########################################################################

sub new {
  my $class = shift;
  $class = ref($class) || $class;
  my $self = $class->SUPER::new (@_);

  $self->{read_metas} = { };

  bless ($self, $class);
  $self;
}

###########################################################################

sub base_edit_form {
  my $self = shift;
  my $q = shift;

  my $form;
  if ($q->param ('upload')) {
    $form = $q->start_multipart_form();
  } else {
    $form = $q->startform();
  }

  $form .= q{
    <p>&nbsp;</p>
    <table>
  };

  # read the text from the file, or from the CGI parameters for fileless
  # edits.
  my $text = $self->get_item_text ($q);

  if (!$q->param ('nometas')) {
    $form .= $self->edit_metadata_ui($q);
  }

  $form .= "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\n\n";

  if ($q->param ('upload')) {
    $form .= $q->hidden(-name=>'upload',-value=>'1');

    $form .= $q->Tr ("<td> Upload file: </td>"
    	. $q->td ( $q->filefield (-name => 'upload_file',
		-default => '',
		-size => 50,
		-maxlength => 256)));

    $form .= q{
        <tr><td></td><td> <p>

	<a href="__REINVOKEALL__upload=0__">[Edit file in-page]</a>

	</p> </td></tr>
    };

  } else {
    my @txtfrom;

    if ($self->is_media($self->{filename})) {
      $form .= $q->hidden(-name=>'upload',-value=>'0');
      @txtfrom = $q->radio_group (-name => 'text_from',
		  -values => [
			  'Load from URL',
			  ],
		  -default => 'Load from URL');

    } else {
      $form .= $q->hidden(-name=>'upload',-value=>'0');
      @txtfrom = $q->radio_group (-name => 'text_from',
		  -values => [
			  'Load from URL',
			  'Textbox'
			  ], -default => 'Textbox');
    }

    if (!$self->is_media($self->{filename})) {
      $form .= $q->Tr ($q->td ({'-valign'=>'top'}, $txtfrom[1] . ":")
	. $q->td ( $q->textarea (-name => 'upload_text',
		-id => 'upload_text',
		-default => $text,
		-rows => 20,
		-columns => 120,
		-class => 'wm_textarea',
		-onkeyup => 'ReloadTextDiv();'
		)
      	. "<p><a href='javascript:OpenPreviewWindow();'>[Live "
	. "HTML preview window]</a> <em>(requires Javascript)</em></p>"
	));
    }

    $form .= "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\n\n";

    $form .= $q->Tr ($q->td ({'-valign'=>'top'}, $txtfrom[0] . ":")
	. $q->td ( $q->textfield (-name => 'upload_url',
		-class => 'wm_textfield',
		-size => 65, -default => '')
	. q{
	      <p class=note>
	      (Note: "load from URL" has not been implemented yet.
	      Do not use it. TODO)
	      </p>
	}
	));

    $form .= "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\n\n";

    $form .= q{
        <tr><td><p>Upload from disk:</p></td><td><p>

	<a href="__REINVOKEALL__dump=1__" target=dumper>[Display raw file]</a>

	&nbsp;
	&nbsp;
	&nbsp;
	<a href="__REINVOKEALL__upload=1__">[Upload new file]</a>

	</p> </td></tr>
    };
  }

  $form .= "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\n\n";

  # $form .= $q->Tr ($q->td ("Link text:")
      # . $q->td ( $q->textfield (-name => 'link_text',
	      # -class => 'wm_textfield',
	      # -size => 65,
	      # -default => '')));
    
  $form .= "<tr><td></td><td>";

  $form .= $q->hidden(-name=>'step',-value=>'editing')
      # . $q->submit(-name=>'Preview',-value=>'Preview')
      # . "&nbsp;"
      . $q->submit(-name=>'Save',-value=>'Save')
      . "&nbsp;"
      . $self->cgi_hidden_items ($q);

  $form .= $self->std_cgi_hidden_items($q);
  $form .= $q->endform();

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

  $form;
}

# ---------------------------------------------------------------------------

sub edit_metadata_ui {
  my ($self, $q) = @_;

  my $form = "<tr><td width=120>"
      . "Title:"
      . "</td><td>"
      . $q->textfield (-name => 'm_title',
	      -class => 'wm_textfield',
	      -size => 65,
	      -default => $self->{read_metas}->{title})
      . "</td></tr>";

  if ($q->param ('allmetadata')) {
    $form .=

	"<tr><td>&nbsp;</td><td>&nbsp;</td></tr>"
      . "<tr><td></td><td><h2>Other Metadata:</h2></td></tr>"

      . $q->Tr ($q->td ($q->p ("Section:"))
	      . $q->td ( $q->textfield (-name => 'm_section',
		      -class => 'wm_textfield',
		      -default => $self->{read_metas}->{section})))

      . $q->Tr ( $q->td ("Score:")
	      . $q->td ( $q->textfield (-name => 'm_score',
		      -class => 'wm_textfield',
		      -default => $self->{read_metas}->{score})))

      . $q->Tr ( $q->td ({'-valign' => 'top'}, "Abstract:")
	      . $q->td ( $q->textarea (-name => 'm_abstract',
		      -default => $self->{read_metas}->{abstract},
		      -class => 'wm_textarea',
		      -rows => 5,
		      -columns => 80)))
      . $q->Tr ( $q->td ("Up:")
	      . $q->td ( $q->textfield (-name => 'm_up',
		      -class => 'wm_textfield',
		      -default => $self->{read_metas}->{up})))
      . $q->Tr ( $q->td ("Author:")
	      . $q->td ( $q->textfield (-name => 'm_author',
		      -class => 'wm_textfield',
		      -size => 65,
		      -default => $self->{read_metas}->{author})));

    $form .= q{

	<tr><td>
	</td><td>
	<p>
	<a href="__REINVOKEALL__allmetadata=0__">
	[Less Metadata...]</a>
	</p>
	</td></tr>
    };

  } else {
    $form .= q{

	<tr><td>
	</td><td>
	<p>
	<a href="__REINVOKEALL__allmetadata=1__">
	[More Metadata...]</a>
	</p>
	</td></tr>

    };
  }

  if ($self->is_media($self->{filename})) {
    $form .= q{

	<tr><td>
	</td><td>
	<p class=note>

	(Note: since this is a non-text item, this metadata cannot be stored in
	the content file itself.  Instead, it will be stored in a <a
	href=http://webmake.taint.org/doc/metatable.html>metatable</a> called
	<em>metadata.xml</em> in the top-level directory.  You may need to modify
	the WebMake file for this site to read this file.)

        </p>
	</td></tr>
    };
  }

  return $form;
}

# ---------------------------------------------------------------------------

sub write_dump_page
{
  my $self = shift;
  my $q = $self->{q};

  # print a header
  my $ctype = 'application/octet-stream'; # default
  if ($self->is_media($self->{filename})) {
    if ($self->{filename} =~ /\.gif$/i) { $ctype = 'image/gif'; }
    if ($self->{filename} =~ /\.png$/i) { $ctype = 'image/png'; }
    if ($self->{filename} =~ /\.jpe?g?$/i) { $ctype = 'image/jpeg'; }
    else { $ctype = 'application/octet-stream'; }
  } else {
    $ctype = 'text/plain';
  }

  print "Content-Type: $ctype\r\n\r\n";
  print $self->get_item_text ($q);
  return '';
}

# ---------------------------------------------------------------------------

sub write_preview_page
{
  my $self = shift;
  my $q = $self->{q};

  "TODO";
}

###########################################################################

sub create_wmmetas {
  my ($self) = @_;
  my $q = $self->{q};

  $self->{wmmetas} = '';

  if ($q->param ('nometas')) { return 1; }

  foreach my $name ($q->param()) {
    next unless ($name =~ /^m_(\S+)/);
    my $metaname = $1; $metaname =~ s/\"/_/gs;

    my $val = $q->param ($name);
    next if ($val =~ /^\s*$/);
    $val =~ s/<(\/\s*wmmeta\s*>)/\&lt;$1/gs; # escape end-of-metadata tags

    $self->{wmmetas} .= "<wmmeta name=\"$metaname\">$val</wmmeta>\n";
  }

  1;
}

# ---------------------------------------------------------------------------

sub strip_wmmetas {
  my ($self, $t) = @_;
  return $t if (!defined $t);
  return $t if ($self->{q}->param ('nometas'));

  $t =~ s/\s*<wmmeta\s*name=\"([^\"]+)\"\s*>(.*?)<\/\s*wmmeta\s*>\s*/
  	$self->_strip_wmmeta_item ($1, $2); /gies;

  $t =~ s/\s*<wmmeta\s*name=([^\s>]+)\s*>(.*?)<\/\s*wmmeta\s*>\s*/
  	$self->_strip_wmmeta_item ($1, $2); /gies;

  $t =~ s/\s*<wmmeta\s*name=\"?([^\">]+?)\"?\s+value=\"?([^\">]+?)\"?\s*\/>\s*/
  	$self->_strip_wmmeta_item ($1, $2); /gies;

  $t;
}

sub _strip_wmmeta_item {
  my ($self, $name, $val) = @_;
  $name =~ tr!A-Z!a-z!;
  $self->{read_metas}->{$name} = $val;
  return '';
}

###########################################################################

1;
