package Img2Html;
use strict;
use Exporter;

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
#	This script turns pictures of various formats into html-tables with coloured cells.
#
#	img to table heuristic courtesy of Randal L. Schwartz
#	source: http://www.buttonhome.org/docs/perl101/articles/webtech/wta0009.htm
#
#
#
# -Requirements: 	ELinks 0.12pre5 (so that the embedded perl interpreter can
#									 dynamically load modules)	
#					ImageMagick + PerlMagick (Image::Magick module)
#
# -Installation:	just put this script in ~/.elinks
#					then add:
#						use lib "$ENV{HOME}/.elinks"; #for Img2Html uses a few modules
#						use Img2Html;
#					  at the beginning of hooks.pl
#					and add:
#						$html = process_Img2Html($url, $html);
#					  at the beginning of the pre_format_html_hook function
#
#
# -MacOSX:	installing PerlMagick on Snow Leopard is quite a mystic experience. After
#			having fought for several hours, i finally managed to do it.
#			Just:	-Install ImageMagick from ports (sudo port install ImageMagick)
#					-Download the corresponding ImageMagick source on the web
#						('sudo port info ImageMagick' will give you the version number)
#					-go into the src/PerlMagick folder, and follow the install instruction
#				
#			installing elinks is quite tricky as well. Just (not really sure it works):
#					-sudo port install elinks-devel (it will fail)
#					-cd `port dir elinks-devel`
#					-cd work
#					-open -a TextEdit src/scripting/perl/hooks.h
#					  then add:
#						#undef LIST_HEAD
#						#define LIST_HEAD(x) x *next; x *prev
#					-from https://trac.macports.org/ticket/22669
#						% sudo make clean
#						% sudo make -j2 all
#
#
# -Tweaking:	you can change the aspect-ratio for image around line 190
#
#
# -FINALLY: some page containing a random painting by Van Gogh for testing purposes
#					http://www.picturalissime.com/g/van_gogh_bles_jaunes_l.htm
#
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #


use CGI qw(:all);
#use CGI::Carp qw(fatalsToBrowser);

use URI::URL;
use HTML::PullParser();

use Image::Magick;
use LWP::Simple qw/get/;

our @ISA= qw( Exporter );

# these are exported by default.
our @EXPORT = qw( process_Img2Html );

sub process_Img2Html
{
	my $url = shift;
	my $html = shift;
	my $new_html = "";

	#$base =~ s/^(\w+:\/\/.*?)\/?/"${1}\/"/;# added trailing slash
	
	my $parser = HTML::PullParser->new( doc => $html,
										start => '"S", tagname, skipped_text, attr, text',
										end => '"E", tagname, skipped_text, attr, text');
	
	my $current_href_link = "";#marks the fact we're in the middle of a-href element -- or not.
	my $captured_source = "";
	
	
	while (my $token = $parser->get_token) {
		my $skipped = $token->[2];
		$new_html = $new_html . $skipped;
		
		my $token_type = $token->[0];
		
	#	print STDERR $token_type, "   :   ", $token->[1], "    :    ", $token->[4], "\n";
		#print STDERR $token->[4], "\n";
		
		#for opening tags
		if ($token_type eq "S") {
			my $tag_name = $token->[1];

			
			unless ($tag_name eq "a" or $tag_name eq "img") {
				#then we're not interested in this element and should leave it unchanged
				$new_html = $new_html . $token->[4];
				#print STDERR $token_type, "   :   ", $token->[1], "    :    ", $token->[4], "\n";
				
			} else {
	
				#mark the fact we're right in the middle of a a-href element;
				if ($tag_name eq "a") {
					#print STDERR $token_type, "   :   ", $token->[1], "    :    ", $token->[4], "\n";
					$current_href_link = $token->[3]{href};
					$captured_source = $captured_source . $token->[4];
				}
			
				if ($tag_name eq "img") {#img elements don't have an ending-tag
				#print STDERR "yayaya\n";
					#get the img absolute url
					my $img_src = $token->[3]{src};
					my $img_url = URI->new_abs($img_src, $url)->canonical;
					
				#	print STDERR $img_src, "    ", $url, "     ", $img_url, "\n";
					
					#get the link the image points to (in case we're in the middle of a a-href element)
					my $img_href = "";
					if ($current_href_link ne "") {
						$img_href = $current_href_link; 
					}
					
					my $img_table = &html_table_from_img($img_url, $img_href);
					#print STDERR $img_table, "\n\n";

					$captured_source = $img_table;
			

				}
				
			}

		}
		
		
		#for closing tags
		if ($token_type eq "E") {
			my $tag_name = $token->[1];
			
			#marks the fact we reached the end of a a-href element;
			if ($tag_name eq "a") {
				$current_href_link = "";
				
			}
			
			if ($captured_source ne "") {
				$new_html = $new_html . $captured_source;
				$captured_source = "";
			}
			else {
				#then we're not interested in this element and should leave it unchanged
				$new_html = $new_html . $token->[4];
			}
		}
	}
	
	return $new_html;
}

sub html_table_from_img
{	
	my $img_url = shift;
	my $img_link = shift;
	my $img_file = "$ENV{HOME}/.elinks/Img2Html_tmp_pic";
	
	my $result;


	
	my $data = get $img_url;
	if ($data) {
		open (FH, ">$img_file");
		binmode (FH);
		print FH $data;
		close (FH);
	}
	
	
	my $im = Image::Magick->new or die "Cannot create im: $!";

	$_ and die "cannot read: $_" for $im->Read($img_file);

	$_ and die "cannot set magick: $_" for $im->Set(magick => 'rgb');

	#adapt this to your term/screen configuration so that a pic in a graphical browser has the same aspect
	#in elinks
	my $width = $im->Get('width')/15;
	my $height = $im->Get('height')/13;

	$im->Scale(width => "${width}");
	$im->Scale(height => "${height}");


	my @image = unpack "C*", $im->ImageToBlob; # rgb triples

#	seek DATA, 0, 0;
#	@ARGV = "<&DATA" unless @ARGV;
#	my $string = join "", <ARGV>;
#
#	$string =~ tr/!-\x7e//cd;
#	my @string = map {
#	  /[<>&\"]/
#	    ? sprintf "&#%d;", ord $_
#	      : $_;
#	} split //, $string;
#	@string = "_" unless @string;
#	my $which = -1;
	
	#open (OUTFILE, ">$ENV{HOME}/.elinks/out.txt");

	#print OUTFILE header, start_html(
	#                         -title => "Test",
	#                         -text => '#88ff88',
	#                        );
	
	

	return table({
	             Cellspacing => 0,
	             Cellpadding => 0,
	             Border => 0,
	            }, join "\n",
	            map {
	              Tr(join "",
	                 map {
	                   my ($r,$g,$b) = splice @image, 0, 3;
	                   #$which = 0 if ++$which >= @string;
	                   td({
	                       Bgcolor => sprintf("#%02x%02x%02x", $r, $g, $b),
	                      }, "&nbsp"
	                     );
	                 } 1..$width)
	            } 1..$height);

}

# for DATA above
__END__