package mod_clock;

#
# $Id$
#

use strict;

use GD;
use USBLCD;
use POSIX qw( strftime );



### Globals
###

my %M_INFO = (
    'graph'	=> 1,
    'alarm'	=> undef,
    'event'	=> undef,
    'update'	=> 100
);

my $M_IMAGES_DIR;
my @M_IM_DIGITS;
my $M_CLOCK;
my $M_TICK_COUNT;
my $M_AVG_TICKS;



### Module methods
###

sub draw_clock($$) {
    my $usblcd = shift;
    my $full_update = shift;

    my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($M_CLOCK);

    my $im =  new GD::Image(122, 32);

    my $white = $im->colorAllocate(255, 255, 255);
    my $black = $im->colorAllocate(0, 0, 0);

    $im->copy($M_IM_DIGITS[$hour / 10], 0 + 19 * 0, 0, 0, 0, 16, 24);
    $im->copy($M_IM_DIGITS[$hour % 10], 0 + 18 * 1, 0, 0, 0, 16, 24);
    $im->copy($M_IM_DIGITS[$min / 10], 7 + 18 * 2, 0, 0, 0, 16, 24);
    $im->copy($M_IM_DIGITS[$min % 10], 7 + 18 * 3, 0, 0, 0, 16, 24);
    $im->copy($M_IM_DIGITS[$sec / 10], 14 + 18 * 4, 0, 0, 0, 16, 24);
    $im->copy($M_IM_DIGITS[$sec % 10], 14 + 18 * 5, 0, 0, 0, 16, 24);

    if ($M_TICK_COUNT < int($M_AVG_TICKS / 2)) {
	$im->filledEllipse(39, 6, 4, 4, $black);
	$im->filledEllipse(37, 18, 4, 4, $black);
    }
    $im->filledEllipse(81, 20, 4, 4, $black);

    my $date_str = strftime("%a %e %b %Y", $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst);

    $im->string(gdTinyFont, (122 - (length($date_str) * &gdTinyFont->width)) / 2, 24, $date_str, $black);

    if ($full_update) {
	$usblcd->bitbltgd(0, 0, $im);
    }
    else {
	my $im_part =  new GD::Image(16, 24);
	$im_part->copy($im, 0, 0, 32, 0, 16, 24);
	$usblcd->bitbltgd(32, 0, $im_part);
    }
}



### Module interface
###

sub init(%) {
    my %init_params = @_;

    # FixMe: test images
    $M_IMAGES_DIR = $init_params{'images_dir'};

    return () unless -d $M_IMAGES_DIR;
    for (my $i = 0; $i < 10; $i++) {
	return () unless -f "$M_IMAGES_DIR/digit$i.png";
    }

    $M_AVG_TICKS = 10;

    return %M_INFO;
}


sub focus($) {
    my $usblcd = shift;

    return &main::M_FOCUS_REJECT;
}


sub enter($) {
    my $usblcd = shift;
    my $i;

    for ($i = 0; $i < 10; $i++) {
	$M_IM_DIGITS[$i] = GD::Image->new("$M_IMAGES_DIR/digit$i.png");
    }

    $M_CLOCK = time;
    $M_TICK_COUNT = 0;

    draw_clock($usblcd, 1);
}


sub leave($) {
    my $usblcd = shift;

    for (my $i = 0; $i < 10; $i++) {
	$M_IM_DIGITS[$i] = undef;
    }
}


sub update($) {
    my $usblcd = shift;

    my $clock = time;
    if ($clock > $M_CLOCK) {
	$M_AVG_TICKS = ($M_AVG_TICKS + $M_TICK_COUNT) / 2;
	$M_TICK_COUNT = 0;
	$M_CLOCK = $clock;
	draw_clock($usblcd, 1);
    }
    else {
	draw_clock($usblcd, 0);
    }

    $M_TICK_COUNT++;
}


1;
