#!/usr/bin/perl -w

use strict;
use warnings;
use lib "../lib";
use Tk;
use Tk::HyperText;
use LWP::Simple;
use MIME::Base64 qw(encode_base64);
use Data::Dumper;

my $curPage = '';

my $mw = MainWindow->new (
	-title => 'Demo',
);
$mw->geometry ('640x480');

my $topFrame = $mw->Frame->pack (-side => 'top', -fill => 'x');
my $mainFrame = $mw->Frame->pack (-side => 'top', -fill => 'both', -expand => 1);

$topFrame->Button (
	-text => 'Reload',
	-command => sub {
		&loadPage($curPage);
	},
)->pack (-side => 'left');
$topFrame->Button (
	-text => 'Home',
	-command => sub {
		&loadPage('index.html');
	},
)->pack (-side => 'left');
$topFrame->Button (
	-text => 'Clear History',
	-command => sub {
		&clearHistory();
	},
)->pack (-side => 'left');

my $html = $mainFrame->Scrolled ('HyperText',
	-scrollbars => 'e',
	-wrap       => 'word',
)->pack (-fill => 'both', -expand => 1);

$html->setHandler (Title    => \&onTitle);
$html->setHandler (Resource => \&onResource);
$html->setHandler (Submit   => \&onSubmit);
&loadPage('index.html');

$mw->bind ('<Control-s>', sub {
	print $html->getText(1) . "\n";
});
$mw->bind ('<Control-t>', sub {
	print $html->getText() . "\n";
});

sub onTitle {
	my ($cw,$title) = @_;

	$mw->configure (-title => $title);
}

sub onSubmit {
	my ($cw,%info) = @_;

	print "Submitted form $info{form}: " . Dumper(\%info);
	&loadPage($info{action});
}

sub onResource {
	my ($cw,%info) = @_;

	if ($info{tag} eq 'a') {
		# Hyperlink
		if ($info{target} ne '_blank') {
			if ($info{href} =~ /^http/i) {
				my $code = get $info{href};
				$html->loadString($code);
			}
			else {
				&loadPage ($info{href});
			}
		}
		else {
			my $htmlview = 'start';
			if ($^O !~ /win32/i) {
				my @try = ("htmlview","firefox","mozilla","opera");
				foreach my $t (@try) {
					my $res = system("which $t");
					if ($res == 0) {
						$htmlview = $t;
						last;
					}
				}

				if ($htmlview eq 'start') {
					$htmlview = undef;
				}
			}

			if (defined $htmlview) {
				system("$htmlview \"$info{href}\"");
			}
			else {
				$mw->messageBox (
					-title   => 'Error',
					-type    => 'Ok',
					-icon    => 'error',
					-message => "Couldn't open hyperlink: no suitable browser found!",
				);
			}
		}
	}
	elsif ($info{tag} eq 'img') {
		# Fetching an image.
		my $src = $info{src};
		if ($src =~ /^http/i) {
			my $bin = get $src;
			my $enc = encode_base64 ($bin);
			return $enc;
		}
		else {
			if (-f "./demo/$src") {
				open (READ, "./demo/$src");
				binmode READ;
				my @bin = <READ>;
				close (READ);
				chomp @bin;

				my $enc = encode_base64 (join("\n",@bin));
				return $enc;
			}
		}
	}

	return undef;
}

sub loadPage {
	my $page = shift;

	$curPage = $page;

	if (-f "./demo/$page") {
		open (READ, "./demo/$page");
		my @html = <READ>;
		close (READ);
		chomp @html;

		$html->loadString(join("\n",@html));
	}
	else {
		$html->loadString("<h1>404 Page Not Found</h1>");
	}
}

sub clearHistory {
	$html->clearHistory();
}

MainLoop;
