#!/usr/bin/perl -w

use strict;
use warnings;

use Curses::UI;
use Data::Dumper;

# simple mail box format parser
sub read_mbox($) {
	my @data;
	my $file = shift;
	my $state = 0;
	open my $fh, ("<$file") or die "Couldn't open $file: $!\n";
	my $hashref = {};
	foreach my $line (<$fh>) {
		if ($line =~ /^From / || $state == 1) {
			if ($state == 2) {
				#split the header fields:
				$hashref->{header} =~ s/\n\s/ /gs;
				foreach my $fields (split "\n", $hashref->{header}) {
					if ($fields =~ /(\w+):(.+)/) {
						$hashref->{lc($1)} = $2;
					}
				}
				push @data, $hashref;
				$hashref = {};
			}
			$state = 1;
			$hashref->{header} .= $line;
		}
		if ($line =~ /^$/ || $state == 2) {
			$hashref->{body} .= $line unless $state != 2;
			$state = 2;
		}
	}
	close $fh or warn "Couldn't close $file: $!\n";

	return @data;
}

### Curses::UI Setup:

my $cui = new Curses::UI(
			 -clear_on_exit => 0,
			 -color_support => 1,
			 );

my $mainw = $cui->add('Mainwindow',
	  'Window',
	  -border => 1,
	  -bfg => "red",
	  -title => "Yet Another Mail Reader 0.001",
	  );

my $max_height = $mainw->height();
my $max_width = $mainw->width();

my $lbox = $mainw->add('List',
	  'Listbox',
	   -fg => "white",
	   -height => int ($max_height / 2),
	  );

my $textbox = $mainw->add('textbox',
	  'TextViewer',
	   -fg => "white",
	   -border => 1,
	   -y => ($max_height / 2),
	   -height => int ($max_height / 2),
	  );

### MAIN ###

$cui->set_binding ( sub { exit 0 } , "\cQ", "\cC");
$cui->set_binding ( sub { 
			$cui->dialog("2004 (c) by Marcus Thiesen");
			} , "\cA");

$lbox->set_binding( sub { $textbox->focus() }, "\t");

$cui->status("Reading mails...");
my @mails = read_mbox($ARGV[0]);
$cui->nostatus();

$lbox->onSelectionChange(
	sub {
		my $id = $lbox->get_active_id();
		my $text = "";
		$text .= "From:    " . $mails[$id]->{from} . "\n";
		$text .= "To:      " . $mails[$id]->{to} . "\n";
		$text .= "Subject: " . $mails[$id]->{subject} . "\n";
		$text .= "-"x($max_width-5) . "\n";
		$text .= $mails[$id]->{body};
		$textbox->text($text);
	}
);

my @subjects;
push(@subjects, $_->{subject}) for @mails;

$lbox->values(\@subjects);

$lbox->focus();
$cui->mainloop();
