package KITTENWEB::RENDER;
sub renderempty { # text, name
    return $_[0]?$_[0]:"Please define $_[1].";
}
# render page
$WikiWord="([A-Z]+[a-z]*[A-Z]+[A-Za-z]*)";

sub renderitemize {		# rawpagedata
    my ($page) = @_;
    my ($state, $l, $depth, $newdepth, $outpage);
    $state = "none";
    $outpage = "";
    while($page =~ /.*/g) {
	$l = $&;
	next if ($l eq "");
	
	if ($l =~ s/^(	+)\*//) {
	    $newdepth=length($1);
	    if ($state eq "none") {
		$state="<ul>";
		$depth=$newdepth;
		$outpage .= "<ul>\n" x $depth;
	    } elsif ($depth < $newdepth) {
		$outpage .= "<ul>\n" x ($newdepth-$depth);
		$depth = $newdepth;	    
	    } elsif ($depth > $newdepth) {
		$outpage .= "</ul>\n" x ($depth-$newdepth);
		$depth = $newdepth;
	    }
	    $outpage .= "<li> $l\n";
	} else {
	    if ($state eq "<ul>") {
		$outpage .= "</ul>\n" x $depth;
		$state = "none"; $depth=0;
	    }
	    $outpage .= $l . "\n";
	}
    }
    return $outpage . "</ul>\n" x $depth;
}

sub rendersafe { # rawpagedata
    my($rawpagedata) = @_;
    $rawpagedata =~ s/&/&amp;/g;
    $rawpagedata =~ s/</&lt;/g;
    $rawpagedata =~ s/>/&gt;/g;
    return $rawpagedata;
}

sub renderhtml { # rawpagedata
    my($rawpagedata) = @_;
    $rawpagedata = &rendersafe($rawpagedata);
    $rawpagedata =~ s/\n----*/\n<hr>/g;
    $rawpagedata =~ s/\n\n/\n<p>\n/g;
    $rawpagedata = &renderitemize($rawpagedata);
    return $rawpagedata;
}


sub replaceword { # db, word, pw
    my ($db,$word,$pw) = @_;
    my (%ldb,%pdb);
    tie %ldb, STASH, $db, "link";
    return qq{<a href="$ldb{$word}">$word</a>} if exists $ldb{$word};
    untie %ldb;
    tie %pdb, STASH, $db, "page";
    return qq{<a href="lookup=$word$pw">$word</a>} if exists $pdb{$word};
    return qq{$word<a href="edit=$word$pw">?</a>};
}

# external
sub renderpage { # db, raw page data, pagename, password
    my($db, $rawpagedata, $pagename, $pw)=@_;

    $rawpagedata =  &renderhtml($rawpagedata);
    $rawpagedata =~ s#$WikiWord#&replaceword($db,$1,$pw)#ge;

    return " ".$rawpagedata.qq{
<hr>
<a href="edit=$pagename$pw">Edit</a>
<a href="refs=$pagename$pw">Refs</a><hr>
<a href="editlinks=$pagename$pw">Edit Embedded Links</a>
};
}

# avoid generating duplicates
sub getrefs { # pagedata
    my(%refs,@reflist);
    while ($_[0] =~ /$WikiWord/og) {
	push(@reflist,$1) if (!defined($refs{$1}));
	$refs{$1} = 1;
    }
    return @reflist;
}
