#!/usr/bin/perl
# (c) 2008-2010 Takeshi Hamasaki
#

use Tk;
use Tk::Pane;
use File::Basename;
use strict;
use Encode qw(decode);

#
#  ---   global valiables
#
my $myname = basename($0, ".pl");
my $CategoryFile;
my @category;
my $ncateg;

my $ntitle;

my @titleLabel;
my @titleTextLine;

my @titleText;
my @before_categ;
my @categLabel;
my @after_categ;

my @categ_on_off;

# geometories etc., for display
my $mainWIndowWidth = 925;

my $labelHeight = 8;

my $titleNumberWidth = 3;
my $titleWidth=30;


my $lineNumberStart = 1;
my $gridClmnChkBtnStart = 2; # 0: line number, 1: title

my $bgColor1 = '#888888';
my $bgColor2 = '#aaaaaa';

# The combination of following 6 elements keep the adujstment of whole display.
my $categoryLabelPadX = 6;
my $categoryLabelBorderWidth = 3;
my $chkBtnPadX = 0;
my $chkBtnBorderWidth = 2;

my $categoryLabelFontSize = 10;
my $chkBtnFontSize = $categoryLabelFontSize-1;

my $fontName = 'さざなみゴシック';
my $textFontSpec = 'さざなみゴシック ' . $categoryLabelFontSize;
my $chkBtnFontSpec = 'さざなみゴシック ' . $chkBtnFontSize;

my $titleBtnPadY = 0;

#
#  ---   error messages
#

my %error_msg = (
	'no_categ' => "No valid category found.",
	'no_title' => "No valid title found.",
	'illegal_categ' => "Not found in available categories."
);

#
#  ---   functions
#
sub read_categories($;)
{
	my ($myCategoryFile) = @_;
	my $categ = 0;
	
	if (-e $myCategoryFile) {
		open(CATEGFILE, $myCategoryFile)
		 or die "No Category setting file.";

		while (<CATEGFILE>) {
			chomp();
			next if /^\#/;

			$category[$categ++] = $_;

		}
		close(CATEGFILE);
	}
	
	return $categ;
}

sub parse_mts($;)
{
	my $t = 0;
	(my $mts_file_name) = @_;
	if ( -e $mts_file_name ) {
		open(MTSFILE, $mts_file_name)
		 or die "Can't open specified MTS file.";
		
		my $before_ctg = "TRUE";
		 
		while (<MTSFILE>) {
			chomp();

			if ( /^AUTHOR:/ ) {
				$before_ctg = "TRUE";
				$t++;
				$before_categ[$t] .= $_ . "\n";

			} elsif ( /^TITLE:/ ) {
				$titleText[$t] = $_;
				$before_categ[$t] .= $_ . "\n";

				
			} elsif ( /^CATEGORY:/ ) {
				my $categ_no=0;
			# todo multiple categories?
				my $c = substr($_, length("CATEGORY: "));
				if ($c ne "") {
				
					FIND_CATEG: for ( ; $categ_no < $ncateg; $categ_no++) {
						if ($c eq $category[$categ_no]) {
							last FIND_CATEG;
						}
					}
					if ( $categ_no < $ncateg ) { 
						$categ_on_off[$t][$categ_no] = 1;
					} else {  # loop over, something wrong.
						print $c . " : " . $error_msg{'illegal_categ'};
					}
				}
				
				$before_ctg = "FALSE";

			} elsif ($before_ctg eq "TRUE" ) {
				$before_categ[$t] .= $_ . "\n";

			} else {
				$after_categ[$t] .= $_ . "\n";
			}
		}
		close(MTSFILE);
		
	} else {
		die "Specified MTS file doesn't exist.";
	}
	
	return $t;

}

sub title_button_press($$;) {
	(my $title_no, my $categPane) = @_;
	$categPane -> messageBox( -type => 'ok',
		-font => $textFontSpec,
		-title => 'Body',
		-width => '80',
		-message => decode('utf-8', $after_categ[$title_no]) );
}

sub writeMTS($$;) {
	
	(my $mts_file_name, my $mainWindow) = @_;


	my $confirm = $mainWindow -> messageBox(
	-type => 'OkCancel',
	-message => 'File will be overwritten. OK?'
	);
	
	if ($confirm eq 'Ok') {

		open(MTSFILE, ">$mts_file_name")
		 or die "Can't open $mts_file_name to write.";
	
		for ( my $t=1; $t <= $ntitle; $t++) {
			print MTSFILE $before_categ[$t];
					
			my $nonCategory = "TRUE";
			for (my $c=0; $c < $ncateg; $c++) {
				if ($categ_on_off[$t][$c] == 1) {
					print MTSFILE "CATEGORY: $category[$c]\n";
					$nonCategory = "FALSE";
				}
			}
			if ($nonCategory eq "TRUE") {
				print MTSFILE "CATEGORY: \n";
			}
	
			print MTSFILE $after_categ[$t];
			
		}
		
		close(MTSFILE);	
	}

}

#
#  ---   main routine
#
$CategoryFile = "$ENV{\"HOME\"}/" . "." . $myname . "/category";
$ncateg = &read_categories($CategoryFile);
if (0 >= $ncateg) {
	die "$error_msg{'no_categ'}";
}

$ntitle = &parse_mts($ARGV[0]);
if (0 >= $ntitle) {
	die "$error_msg{'no_title'}";	
}

my $mw = MainWindow->new();


my @categ_pane;
my @cb;


# --  to line categories up on top
#

my $gridColumn = 0;
my $gridRow = 0;

my $cnp = $mw->Frame(-relief => 'sunken',
	-width => $mainWIndowWidth,
	-height => '10',
	-borderwidth => '1',
	); 

$cnp->Label(
	-width => $titleNumberWidth,
	-text  => 'No.',
	-background => $bgColor1
) -> grid(-row => $gridRow, -column => $gridColumn++);
$cnp->Button(
	-width => $titleWidth,
	-font => $textFontSpec,
	-anchor => 'w',
	-text => "Save MTS File: ". basename($ARGV[0]),
	-command => [ \&writeMTS, $ARGV[0], $mw ]
) -> grid(-row => $gridRow, -column => $gridColumn++);

for (my $c =0; $c < $ncateg; $c++) {
	my $categ_no = 0;
	my $bgcolor;
	if ( ($c % 2) == 0 ) {
			$bgcolor = $bgColor1;
		} else {
			$bgcolor = $bgColor2;
		}

	$categLabel[$categ_no++] = $cnp -> Label(
	-text => decode('utf-8', $category[$c]),
	-font => $textFontSpec,
	-anchor => 'n',
	-wraplength => '1',
	-width => '1', 
	-height => $labelHeight,
	-relief => 'sunken',
	-padx => $categoryLabelPadX,
	-background => $bgcolor,
	-borderwidth => $categoryLabelBorderWidth
	) -> grid(-row => $gridRow, -column=> $gridColumn++);
}

# $cnp -> pack( -side => 'top', -anchor => 'w' , -fill => 'x');
$cnp -> grid( -row => 0, -column => 0, -sticky => 'nw');

# -- titiles, category check buttons.
#

# Scrollable pane.
my $mp = $mw->Scrolled('Pane', Name => 'MainPain',
	-scrollbars => 'osoe',
	-sticky => 'w',
	-gridded => 'x',
	-width => $mainWIndowWidth,
	-height => '700',
	);


for (my $t=$lineNumberStart; $t < $ntitle + $lineNumberStart; $t++) { # line number starts from 1.
#  make a pane for each "TITLE:"
	$categ_pane[$t] = $mp->Frame(-relief => 'sunken',
	-width => $mainWIndowWidth,
	-height => '700',
	-borderwidth => '1'
	); 

	$gridColumn = 0;
	
	$titleLabel[$t] = $categ_pane[$t] -> Label(
	-text  => $t,
	-width => $titleNumberWidth,
	-pady => $titleBtnPadY,
	-background => $bgColor1
	) -> grid( -row => 0, -column => $gridColumn++ );

	my $title;
	if ( length($titleText[$t]) > length("TITLE:") ) {
		$title = substr($titleText[$t], length("TITLE:"));
	} else {
		$title = '（無題）';
	}
	$titleTextLine[$t] = $categ_pane[$t] -> 
		Button (
			-text => decode('utf-8', $title ),
			-font => $textFontSpec,
			-anchor => 'w',
			-width => $titleWidth,
			-pady => $titleBtnPadY,
			-command => [ \&title_button_press, $t, $categ_pane[$t] ]
			
		) -> grid( -row => 0, -column => $gridColumn++ );

	# make check buttons for categories
	my $bgcolor;
	for (my $c=0; $c < $ncateg; $c++) {
		if ( ($c % 2) == 0 ) {
			$bgcolor = $bgColor1;
		} else {
			$bgcolor = $bgColor2;
		}

		$cb[$t][$c] = $categ_pane[$t]-> Checkbutton(
			-variable => \$categ_on_off[$t][$c] ,
			-background => $bgcolor,
			-selectcolor => 'yellow',
			-font => $chkBtnFontSpec,
			-padx => $chkBtnPadX,
			-borderwidth => $chkBtnBorderWidth
			) -> grid( -row => 0, -column => $gridColumn++ );;
	}
	
	$categ_pane[$t]->pack( -side => 'top', -fill => 'x');
}


#$mp->pack( -fill => 'both');
$mp-> grid( -row => 1, -column => 0, -sticky => 'news');

MainLoop;
