#!/usr/bin/perl -w

use strict;
use URI;
use URI::QueryParam;
use WWW::Mechanize;
use YAML;

my $default_username = "AutoKake";
my $default_comment = "Stub page for location search.";

#my $new_page_url = "http://morerandomness.org.uk/openguides/newpage.cgi";
my $new_page_url = "http://london.randomness.org.uk/newpage.cgi";

my $datastr;
open FILE, "rgldata" or die "Can't open rgldata: $!";
while (<FILE>) {
  $datastr .= $_;
}
close FILE;

print "Finished reading in data.\n";

my @data = Load( $datastr );

print "Finished processing YAML.\n";

foreach my $datum ( @data ) {
  if ( $datum && $datum->{pagename} ) {
    my $pagename = $datum->{pagename};
    if ( page_exists( $pagename ) ) {
      print "$pagename already exists; skipping.\n";
    } else {
      makepage( %$datum );
    }
  }
}

sub page_exists {
  my $pagename = shift;
  print "Checking for existence of $pagename...\n";
  my $agent = WWW::Mechanize->new();
  $agent->get( $new_page_url );
  $agent->submit_form(
                       form_number => 2,
                       fields      => {
                                        pagename => $pagename,
                                      },
                     );
  $agent->follow_link( text => "(cancel edit)" );
  my $html = $agent->content();
  if ( $html =~ /We don't have a node called/ ) {
    return 0;
  }
  return 1;
}

sub makepage {
  my %args = @_;
  my $pagename = delete $args{pagename};

  my @splitcats = split( /, */, $args{categories} );
  $args{categories} = join( "\r\n", @splitcats );

  my @splitlocs = split( /, */, $args{locales} );
  $args{locales} = join( "\r\n", @splitlocs );

  $args{content} = $args{summary};
  if ( $args{extra_content} ) {
    $args{content} .= "\r\n\r\n" . $args{extra_content};
  }
  delete $args{extra_content};

  my $username = $args{username} || $default_username;
  my $comment  = $args{comment}  || $default_comment;

  my $u = URI->new( $args{map_link} );
  $args{os_x} = $u->query_param( "x" ) || $u->query_param( "X" );
  $args{os_y} = $u->query_param( "y" ) || $u->query_param( "Y" );

  my $agent = WWW::Mechanize->new();
  $agent->get( $new_page_url );
  $agent->submit_form(
                       form_number => 2,
                       fields      => {
                                        pagename => $pagename,
                                      },
                     );
  $agent->submit_form(
                       form_number => 1,
                       fields      => {
                                        %args,
                                        username => $username,
                                        comment => $comment,
                                        edit_type => "Minor tidying",
                                      },
                       button => "Save",
                     );
  print "Processed $pagename\n";
  return;
}
