#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
use Text::VimColor;
use HTML::TokeParser::Simple;
use HTML::Entities qw(decode_entities);
use Path::Class;

my $html_file = shift;
my $reader = file( $html_file )->openr;
unlink $html_file;
my $writer = file( $html_file )->openw;

my $parser = HTML::TokeParser::Simple->new( $reader );

while( my $token = $parser->get_token ) {

	my $class_name = $token->get_attr( "class" );

	if( $token->is_start_tag( "div" )
		&& ( $class_name && $class_name =~ qr/\bexample\b/ )
	) {
		my $start_tag = $token;
		$start_tag->set_attr( class => $class_name . " synNormal" );
		my @content;
		my $end_tag;
		
		EXAMPLE:
		while( $token = $parser->get_token ) {
			if( $token->is_end_tag( "div" ) ) {
				$end_tag = $token;
				last EXAMPLE;
			}

			if( $token->is_text ) {
				push @content, decode_entities( $token->as_is );
			}
		}

		my $code = join "", @content;
#		say $code;
		my $vim = Text::VimColor->new(
			string => $code,
			filetype => "perl",
			vim_options => [qw( -RXZ -i NONE -u NONE -N -n)],
		);
		my $html = $vim->html;
		$html =~ s/^\s+//;
		$html =~ s/\s+$//;

		print $writer $start_tag->as_is;

		my $lines = $html =~ tr/\n/\n/;

		say $writer "<div class='line_number'>";
		for my $line ( 0 .. $lines ) {
			say $writer "<div>",1 + $line,"</div>";
		}
		say $writer "</div>";

		print $writer "<div class='content'><pre>";
		say $writer $html;
		say $writer "</pre></div>";
		print $writer $end_tag->as_is;
	} else {
		print $writer $token->as_is;
	}
}
