package MT::Plugin::hirosikitextfilter;
use strict;

use MT;
use MT::Plugin;

use HTML::TokeParser;

use vars qw( %textLoc %inTags %inNoBreakTags $procs );

%textLoc = split( ',', 'S,4,E,2,PI,2' );
%inTags =
	split( ',',
		'a,,pre,,script,,object,,embed,'
	);
%inNoBreakTags =
	split( ',',
		'pre,,script,,object,,embed,,'
		. 'textarea,,table,,dl,,menu,,dir,'
	);
$procs = 'http|https|ftp|mailto|gopher';

# show plugin information to main menu
eval( "use Storable;" );
if ( !$@ && MT->can('add_plugin') ) {
	my $plugin = MT::Plugin->new;
	$plugin->description( 'hirosiki text filter.' );
	if ( MT->version_number >= 3.2 ) {
		$plugin->name( 'Hirosiki Text Filter' );
		$plugin->version( '2' );
	} else {
		$plugin->name( 'Hirosiki Text Filter 1' );
	}
	MT->add_plugin( $plugin );
}

MT->add_text_filter(
	'hirosikitextfilter' => {
		label => '&#25913;&#34892;&#12434;&#22793;&#25563;&#65291;&#65333;&#65330;&#65324;&#33258;&#21205;&#12522;&#12531;&#12463;&#65288;&#12402;&#12429;&#24335;&#65289;',
		on_format => \&hirosiki_text_filter,
	}
);

sub hirosiki_text_filter {
	my $str = shift || '';
	$str =~ s/\x0D\x0A|\x0D|\x0A/\n/g;

	my $r = '';
	my %lev = split( ',', 'noLink,0,noBreak,0' );
	my $lastSTag = '';
	my $lastETag = '';

	my $p = HTML::TokeParser->new( \$str );
	while ( my $t = $p->get_token ) {
		my $mode = $t->[0];
		my $perhapsTagName = $t->[1];
		my $out =
			( exists $textLoc{ $t->[0] } ) ?
			$t->[ $textLoc{ $t->[0] } ]
			: $t->[ 1 ]
		;
		if ( $mode eq 'T' ) {
			if ( $lev{'noBreak'} == 0 ) {
				$out =~ s!\n!<br />\n!g;
				$out =~ s!^<br />!!
					if (
						( exists $inNoBreakTags{ $lastETag } )
						|| ( $lastETag =~ /^(?:p|br)$/ )
						|| ( $lastSTag =~ /^(?:p|br)$/ )
					);
			}
			if ( $lev{'noLink'} == 0 ) {
				$out =~ s!
						((?:$procs):[^\x00-\x20"()<>\x7F-\xFF]+)
					!
						my $u = $1;
						my $o = $1;
						$u =~ s/\&/\&amp;/g;
						"<a href=\"$o\">$u</a>";
					!gxe;
			}
		}
		$lastSTag = '';
		if ( $mode eq 'S' ) {
			$lastSTag = $perhapsTagName;
			$lev{'noLink'}++ if ( exists $inTags{ $perhapsTagName } );
			$lev{'noBreak'}++ if ( exists $inNoBreakTags{ $perhapsTagName } );
		}
		$lastETag = '';
		if ( $mode eq 'E' ) {
			$lastETag = $perhapsTagName;
			$lev{'noLink'}--
				if (
					( exists $inTags{ $perhapsTagName } )
					&& ( $lev{'noLink'} > 0 )
				);
			$lev{'noBreak'}--
				if (
					( exists $inNoBreakTags{ $perhapsTagName } )
					&& ( $lev{'noBreak'} > 0 )
				);
		}
		$r .= $out;
	}

	$r;
}

1;
