package Shiar_Sheet::FormatChar;

use 5.010;
use strict;
use warnings;
use utf8;

use Data::Dump 'pp';
use PLP::Functions 'EscapeHTML';

our $VERSION = '1.08';

our $uc = do 'unicode-char.inc.pl';

sub new {
	my ($class) = @_;
	bless { anno => ['di', 0], style => 'di' }, $class;
}

sub glyph_info {
	my ($self, $codepoint) = @_;
	return $uc->{chr $codepoint} || eval {
		require Unicode::UCD;
		if (my $fullinfo = Unicode::UCD::charinfo($codepoint)) {
			return [@$fullinfo{qw/category name - string/}];
		}
	} || [];
}

sub glyph_html {
	my ($self, $char) = @_;
	my $codepoint = ord $char;
	my $info = $self->glyph_info($codepoint);
	my ($class, $name, $mnem, $entity, $string) = @$info;

	my $cell = EscapeHTML($string || $char);
	my $title = sprintf 'U+%04X%s', $codepoint, !!$name && " ($name)";

	$cell = "<span>$cell</span>" if $class and $class =~ /\bZs\b/;
	$cell = '&nbsp;' if $cell eq '';

	return ($cell, EscapeHTML($title), !!$class && "X $class", $mnem, $entity);
}

sub glyphs_html {
	my $self = shift;

	return $self->glyph_html(@_) if length $_[0] <= 1;

	my @chars = map { [ $self->glyph_html($_) ] } split //, $_[0];
	return (
		EscapeHTML($_[0]), # cell
		join(' | ', map { $_->[1] } @chars), # title
		$chars[0][2], # class
		join(' ',  map { $_->[3] // '…' } @chars), # digraph
	);
}

sub glyph_cell {
	my ($self, $char) = @_;
	return sprintf('<td class="%3$s" title="%2$s">%s', $self->glyph_html($char));
}

sub cell {
	my ($self, $input, $html) = @_;
	my (@class, $title, $cell, $mnem, $entity);

	if ($input eq '-') {
		$cell = '';
	}
	elsif ($input eq '=') {
		push @class, 'u-invalid';
		$cell = '';
	}
	else {{
		push @class, 'X';

		if ($input =~ s/^-//) {
			push @class, 'ex'; # discouraged
		}

		$input =~ s/^\\//;  # escaped char
		($cell, $title, my $class, $mnem, $entity) = $self->glyphs_html($input);
		my $codepoint = ord $input;

		if ($self->{style} eq 'univer') {
			if ($input =~ /\p{age=unassigned}/) {
				# check include for assignments after unicode 6.0 (perl v5.14)
				state $agemap = do 'unicode-age.inc.pl';
				my $version = $agemap->{$codepoint};
				push @class, $version ? 'l2' : 'l1';
			}
			elsif ($input =~ /^\p{in=1.1}*$/) {
				push @class, 'l5';  # first release 1993
			}
			elsif ($input =~ /^\p{in=3.0}*$/) {
				push @class, 'l4';  # 20th century
			}
			elsif ($input =~ /^\p{in=4.1}*$/) {
				push @class, 'l4';  # over 10 years ago
			}
			elsif ($input =~ /^\p{in=6.0}*$/) {
				push @class, 'l3';  # before 2012
			}
			else {
				push @class, 'l2';  # more recent
			}
			next;
		}

		if ($self->{style} eq 'di') {
			if ($mnem and $mnem =~ /…/) {
				# incomplete representation, usually partial
			}
			elsif ($class =~ /\bu-di\b/) {
				push @class, ('l4', 'u-di'); # standard digraph
			}
			elsif ($class =~ /\bu-prop\b/) {
				push @class, ('l3', 'u-prop'); # unofficial
			}
		}
		elsif ($self->{style} eq 'html') {
			if (defined $entity) {
				push @class, ($codepoint <= 0xFF ? 'l4' : 'l3', 'u-html');
			}
		}
		else {
			if ($codepoint <= 0xFF) {
				push @class, 'l4', 'u-lat1';  # latin1
			}
			elsif ($codepoint <= 0xD7FF) {
				push @class, 'l3', 'u-bmp';  # bmp
			}
		}

		if ($input =~ /[ -~]/) {
			push @class, 'l5', 'u-ascii'; # ascii
		}
		elsif ($input =~ /^\p{in=6.0}+$/) {
			push @class, 'l2'; # in unicode 6.0
		}
		else {
			push @class, 'l1'; # any unicode
		}
	}}

	my $anno = '';
	if ($cell ne '') {
		for (@{ $self->{anno} }) {
			if (/html$/) {
				if (defined $entity) {
					$entity = "&$entity;" if /^&/;
					$anno = sprintf(' <small class="digraph">%s</small>', EscapeHTML($entity));
					last;
				}
			}
			elsif ($_ eq 'xml') {
				$anno = sprintf(' <small class="digraph">%s</small>',
					sprintf '#%d', ord($cell)
				);
				last;
			}
			elsif ($_ eq '&xml') {
				$anno = sprintf(' <small class="digraph">%s</small>',
					sprintf '&amp;#%d;', ord($cell)
				);
				last;
			}
			elsif ($_ eq 'di') {
				if (defined $mnem and length $mnem) {
					$anno = sprintf(' <small class="digraph">%s</small>', EscapeHTML($mnem));
					last;
				}
			}
			else {
				if ($_ eq 'hex' or $input =~ /^[^a-zA-Z]$/) {
					$anno = sprintf(' <small class="%s">%04X</small>', 'value', ord $input);
					last;
				}
			}
		}
	}

	return sprintf('<%s>%s%s',
		join(' ', 'td',
			defined $title ? qq{title="$title"}  : (),
			@class ? sprintf('class="%s"', join ' ', @class) : (),
			$html || (),
		),
		$cell eq '' ? '&nbsp;' : $cell,
		$anno,
	);
}

sub row {
	my ($self, $cells) = @_;
	my @html;

	my $colspan = 1;
	for my $cell (@{$cells}) {
		if ($cell =~ s/^\.//) {
			# dot indicates start of a new row
			push @html, '<tr>';
			if ($cell =~ s/^>//) {
				# header cell text follows
				$cell =~ s/_/ /g;  # underscores may be used instead of whitespace (for qw//ability)
				my $class = $cell =~ s/^-// && ' class="ex"';
				$html[-1] .= "<th$class>".($cell || '&nbsp;');
			}
			next;
		}
		elsif ($cell eq '>') {
			# merge this cell to the next column
			$colspan++;
			next;
		}
		elsif ($cell eq '>-') {
			$html[-1] .= '<th>';
			next;
		}
		elsif ($cell =~ m/^</) {
			$html[-1] .= '<td>'.$cell;
			next;
		}

		$html[-1] .= $self->cell($cell,
			$colspan > 1 && qq{colspan="$colspan"},
		);

		$colspan = 1;
	}

	return @html;
}

sub tabletag {
	my ($self) = @_;
	my $class = 'glyphs';
	$class .= ' dilabel' if @{ $self->{anno} };
	return sprintf '<table class="%s">', $class;
}

sub table {
	my ($self, $digraphs) = @_;

	my @rows;

	my @colheads;
	while ($digraphs->[0] !~ /^\./) {
		my $cell = shift @$digraphs or last;
		push @colheads, join('',
			'<',
			$cell =~ s/^-// ? 'td' : 'th',
			$cell =~ s/:(.*)// && qq{ title="$1"},
			$cell =~ s/^>// && ' colspan=2',
			'>',
			$cell eq '_' ? '&nbsp;' : $cell
		);
	}
	push @rows, sprintf '<thead><tr>%s<tbody>', join '', @colheads if @colheads;
	push @rows, $self->row($digraphs);

	return join '', map {"$_\n"} $self->tabletag, @rows, '</table>';
}

sub print {
	my $self = shift;
	while (@_) {
		print '<div class="section">';
		printf '<h2>%s</h2>', shift unless ref $_[0];
		print "\n\n";
		while (ref $_[0] and $_ = shift) {
			print $self->table($_);
		}
		print "\n</div>";
	}
}

sub legend {
	my $self = shift;
	my @classes = $self->{style} eq 'univer' ? (
		[l5 => 'unicode 1.1'],
		[l4 => '20th century'],
		[l3 => 'in 6.0 (2010)'],
		[l2 => 'recent assignments'],
		[l1 => 'proposed'],
		[ex => 'irregular'],
	) : (
		[l5 => 'ascii'],
		[l4 => $self->{style} eq 'di' ? 'digraph' : 'latin1'],
		[l3 => $self->{style} eq 'di' ? 'proposed' : 'HTML4'],
		[l2 => 'unicode ≤6.0'],
		[l1 => 'other unicode'],
		[ex => 'discouraged'],
	);

	return (
		'<div class="legend"><table class="glyphs"><tr>',
		(map { sprintf '<td class="X %s">%s', @{$_} } @classes),
		'</table></div>',
	);
}

1;

