#!/usr/bin/perl

use strict;
use warnings;

use CGI;
use CGI::Carp qw(fatalsToBrowser);
my $query=new CGI;

use HTML::WikiConverter;

my $text = $query->param( "wikitext" );

if( $text ) {
	print "Content-type:text/html; charset=utf-8\n\n<html><head><title>Super amazing wikifier</title></head><body>";

	my( $title, $result, $result_wo_t, @templates ) = convertwikichan( $text );
	print "<h1>Here is your wikified version of «$title»</h1>";
	if( @templates + 0 > 0 ) {
		print "<h2>There were " . ( @templates + 0 ) . " templates detected which you should(must) replace, if you do not want to do that or if it's unnecessary or borked, use the version without replacements at this pages end.</h2>";
	}
	print "<h3>Result:<form><textarea rows=\"50\" cols=\"100\">$result</textarea></form>";
	
	my $cnt = 0;
	foreach ( @templates ) {
		print "<h3>{{Template$cnt}}</h3><form><textarea rows=\"10\" cols=\"100\">$_</textarea></form>";
		$cnt++;
	}

	print "<hr><h3>Result, no teplate replacement:</h3><form><textarea rows=\"50\" cols=\"100\">$result_wo_t</textarea></form>";
	print "</body></html>";
} else {
	print "Content-type:text/html; charset=utf-8\n\n";
	print <<HTML
<html><head><title>Super amazing wikifier</title></head>
<body><h1>Super-amazing wikifier</h1>
<h2><a href="http://wikichan.org/index.php/Super_Amazing_Wikifier">Super Amazing Wikifier: How to use it</a></h2>
<h2>Enter html source code:</h2>
<form method="post" action=""><textarea name="wikitext" id="wikitext" rows="50" cols="100">Paste source here</textarea><br>
<input type="submit" value="Do it!" />
</body>
</html>
HTML
;
}

sub convertwikichan {
	my $html = shift();
	my $wc = new HTML::WikiConverter( 
		dialect => 'MediaWiki',
		base_uri => 'http://wikichan.org/',
		wiki_uri => [
			qr~http://wikichan.org/index.php\?title\=([^&]+)~,
			qr~http://wikichan.org/index.php/(.*)~,
			qr~http://wikichan.org/wiki/(.*)~,
		],
		strip_tags => [ 'br', '~comment', 'head', 'script', 'style' ]
	);
	
	my ( $title, $wikipart ) = ( $html =~ m~<h1 class="firstHeading">(.*?)</h1>(?:.*?)<!-- start content -->(.*)<!-- end content -->~gis );
	
	$wikipart =~ s/http:\/\/web.archive.org\/web\/(?:[0-9a-z_])\///;
	
	if( !$wikipart || $wikipart eq '' ) {
		print( "<html><head><title>Meh.</title></head><body>Something went wrong, maybe preparsing failed, maybe you're just SOL, maybe you entered the wrong stuff. Reread <a href=\"http://wikichan.org/index.php/Super_Amazing_Wikifier\">the tutorial</a> and see if that helps. Make sure you copied <b>all</b> of the source code.</body></html>" );
	} 

	# Edit link remove, quick hack, too lazy to find actual problem.
	$wikipart =~ s/\[<a href="[^"]*" title="[^"]*">edit<\/a>\]//gi;

	# Wikification
	my $wikified = $wc->html2wiki( $wikipart );
	
	# Edit link fuckups
	$wikified =~ s/\[\[index.php\?title=([^&]+)&action=edit/[[$1/gis;


	# Some minor replacements.
	$wikified =~ s/<span class="mw-headline">([^<]*)<\/span>/$1/gis;
	$wikified =~ s/<font color="(?:[^"]*)">([^<]*)<\/font>/$1/gis;

	# Stub
	$wikified =~ s/<div id="stub" class="boilerplate metadata">(.*?)<\/div>/{{Stub}}/gis;
	
	# Thumb images
	$wikified =~ s/<div class="thumb tright">(?:.*?)width:([ 0-9]*)px(?:.*?)Image:([A-Za-z0-9_+-. ]*)(?:.*?)<\/div>([^<]*)<\/div><\/div><\/div>/[[Image:$2 | frame | right | $1px | $3 ]]\n/gis;
	$wikified =~ s/<div class="thumb tleft">(?:.*?)width:([ 0-9]*)px(?:.*?)Image:([A-Za-z0-9_+-. ]*)(?:.*?)<\/div>([^<]*)<\/div><\/div><\/div>/[[Image:$2 | frame | left | $1px | $3 ]]\n/gis;
	$wikified =~ s/\[\[Image:([A-Za-z0-9_+-.]*?)\s([A-Za-z0-9_+-.]*) \| frame \|/[[Image:$1_$2 | frame |/gis;

	# TOC
	$wikified =~ s/{\| id="toc"(?:.*?)\|}/\n__TOC__/gis;

	# Categories
	my %has_cat = ( );
	$wikified .= "\n";
	while( $wikipart =~ /(Category:[^"]*)"/gis ) {
		my $cat_c = $1;
		$cat_c =~ s/ /_/gi;

		if( !$has_cat{$cat_c} ) {
			$has_cat{$cat_c} = 1;
			$wikified .= "\n[[$cat_c]]";
		}
	}

	my $wikified1 = $wikified;
	# Random templates?
	my $cnt = 0;
	my @templates = ( );
	while( $wikified =~ s/({\|(?:.*?)\|})/{{Template$cnt}}/is ) {
		push( @templates, "$1" );
		$cnt += 1;
	}

	return( $title, $wikified, $wikified1, @templates );
}