#! /usr/bin/perl

use strict;
use warnings;

use YAML qw/LoadFile Dump/;
use Mail::Box::Manager;
use Curses::UI;

my $max = 10;

sub quit {
    exit(0);
}

my $mgr = Mail::Box::Manager->new;

my $cui = Curses::UI->new(
    -color_support => 1,
    -debug => 1,
    );
my $main = $cui->add('main', 'Window');

my $config = LoadFile('config.yml');
my %boxes_labels = ();
my @boxes_values = ();
foreach (@{$config}) {
    my ($name) = keys %{$_};
    my $source = $_->{$name}->{source};
    my $value = [$name, $source];
    push @boxes_values, $value;
    $boxes_labels{$value} = $name;
}

my $boxes = $main->add(
    'boxes', 'Listbox',
    -values    => \@boxes_values,
    -labels    => \%boxes_labels,
    -width     => 30,
    -onchange  => \&open_box,
    -border    => 1,
    );

my $summaries = $main->add(
    'summaries', 'Notebook',
    -x      => 31,
    -border => 1,
    );
$summaries->add_page("Cnutt-read");

$boxes->set_binding(sub {$summaries->focus();}, "c", "\t");
$summaries->set_binding(sub {$boxes->focus();}, "c", "\t");
$cui->set_binding(\&quit, "\cQ", "\cC");

$cui->mainloop();

sub open_box {
    my ($widget) = @_;
    my ($selected) = $widget->get();
    my ($name, $source) = @{$selected};

    my $page = $summaries->add_page($name);
    $source =~ s/^~/$ENV{HOME}/;
    my $folder = $mgr->open($source);
    
    my $count = 0;
    my %summaries = ();
    my @keys = ();
    foreach my $message ($folder->messages) {
        last if $count > $max;
        my $subject = $message->get('Subject');
        $summaries{$count} = $subject;
        push @keys, $count;
        $count++;
    }

    my $listbox = $page->add(
        $name, 'Listbox',
        -values    => \@keys,
        -labels    => \%summaries,
        -onchange  => \&open_msg,
        -userdata  => [$page, $name, $source, $folder],
        );
    $listbox->set_binding(\&close_box, "q");

    $summaries->activate_page($name);
    $summaries->focus();

    $summaries->intellidraw();
}

sub close_box {
    my ($widget) = @_;
    my ($page, $name, $source, $folder) = @{$widget->userdata};
    $widget->root->dialog(
        -message => "Close folder",
    );

    $folder->close();
    my $current_page = $summaries->active_page();
    $summaries->activate_page($summaries->prev_page());
    $summaries->delete_page($current_page);

    $summaries->intellidraw();
}

sub open_msg {
    my ($widget) = @_;
    my ($selected) = $widget->get();
    my ($page, $name, $source, $folder) = @{$widget->userdata};

    my $message = $folder->message($selected);
    my $body    = $message->decoded;
    my $subject = $message->get('Subject');

    my $page = $summaries->add_page(substr($subject, 0, 12));
    my $textviewer = $page->add(
        'msg', 'TextViewer',
        -text     => $body,
        -wrapping => 1,
        );

    $summaries->intellidraw();
}

sub focus_boxes {
    $boxes->focus();
}

