# $Id: HTML.pm 375 2008-02-22 19:22:41Z michal $

package Victor::Output::HTML;

use strict;
use warnings;
use open ':locale';

use Exporter;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(&output_html);

use HTML::Parser;

sub output_html {
	my ($opt, $blocks) = @_;
	my $p = HTML::Parser->new(api_version => 3,
		start_h => [\&_start_element, "self,tagname,attr,text,skipped_text"],
		end_document_h => [\&_end_document, "self,skipped_text"]
	);
	$p->utf8_mode(0);
	$p->{blocks} = $blocks;
	$p->{errors} = 0;
	my $need_close = 0;
	if ($opt->{output}) {
		if (ref($opt->{output}) eq "GLOB") {
			$p->{out} = $opt->{output};
		} else {
			open(my $fh, ">", $opt->{output}) || die "can't open $opt->{output}: $!\n";
			$p->{out} = $fh;
			$need_close = 1;
		}
	} else {
		$p->{out} = \*STDOUT;
	}
	open(my $fh, "<", $opt->{orig}) or die;
	$p->parse_file($fh) or die $!;
	close($fh);
	if ($need_close) {
		close($p->{out});
	}
}

sub _start_element {
	my ($self, $tagname, $attr, $text, $skipped_text, $tokens) = @_;
	if ($tagname eq "span" && defined($attr->{id}) &&
		$attr->{id} =~ /^victor_an([0-9]+)/) {{
		my $id = $1;
		if (!defined($self->{blocks}->[$id])) {
			print STDERR "internal error: block #$id not fount in \@blocks\n";
			last;
		}
		my $class = $self->{blocks}->[$id]->{class};
		if (!defined($class)) {
			last;
		}
		if ($text =~ /\bclass="victor_[^"]*"/) {
			$text =~ s/\bclass="victor_[^"]*"/class="victor_$class"/;
		} else {
			$text =~ s/( ?)>$/ class="victor_$class"$1>/;
		}
	}}
	print { $self->{out} } $skipped_text . $text;
}

sub _end_document {
	my ($self,$skipped_text) = @_;;
	print { $self->{out} } $skipped_text;
}

1;
