package Test::Harness::Selenium;
use strictures 1;

use File::Find;
use Socialtext::WikiFixture::Selenese;
use HTML::TableExtract;
use IO::All;

use Test::Builder;
BEGIN {
  package Test::Builder;

  use Class::Method::Modifiers;
  use ExtUtils::MakeMaker qw(prompt);

  if (!$ENV{AUTOMATED_TESTING}) {
    around ok => sub {
      my ($orig, $self) = (shift, shift);
      my $res = $self->$orig(@_);
      unless ($res) {
        if ('y' eq prompt "Well that didn't work, did it. Bail out?", 'y') {
          exit 255;
        }
      }
      return $res;
    };
  }
}

sub new {
  my ($class, $self) = @_;
  bless $self, $class;
}

sub test_directory {
  my ($self, $dir) = @_;
  my @tests = File::Find::Rule->file()->name('*.html')->in($dir);
  $self->run_tests_for($_) for @tests;
}

sub run_tests_for {
  my ($self, $html_file) = @_;
  my $rows = $self->get_rows_for($html_file);
  my $src = Socialtext::WikiFixture::Selenese->new(
    host => $self->{host},
    port => $self->{port},
    browser => $self->{browser},
    browser_url => $self->{browser_url},
  );
  $src->run_test_table($rows);
}

my $te = HTML::TableExtract->new;
sub get_rows_for {
  my ($self, $html_file) = @_;
  my $html = io($html_file)->all;
  $te->parse($html);
  my $table = ($te->tables)[0];
  my @rows = map {
    [ map { $_ eq "\240" ? () : $_ } @$_ ]
  } $table->rows;
  return \@rows;
}

1;
