# Originally written by Alan Harder
# See ChangeLog for list of modifications and contributors.

package SyncTime;

use Tk;
use TkUtils;
use strict;
use vars qw($PREFS $RCFILE $gConfigDlg $VERSION);
$VERSION = $PilotMgr::VERSION;

sub conduitInit
{
    $RCFILE = "SyncTime/SyncTime.prefs";
    &loadPrefs;

    $PREFS->{'lastTime'} = 0
	unless (defined $PREFS->{'lastTime'});
    $PREFS->{'howOften'} = 'Every Sync'
	unless (defined $PREFS->{'howOften'});
}

sub conduitQuit
{
    &savePrefs;
}

sub conduitInfo
{
    return { 'version' => $VERSION,
	     'author' => 'Alan Harder',
	   };
}

sub conduitConfigure
{
    my ($this, $wm) = @_;

    &createConfigDlg($wm) unless (defined $gConfigDlg);

    $gConfigDlg->Popup(-popanchor => 'c', -overanchor => 'c',
		       -popover => $wm);
}

sub createConfigDlg
{
    my ($wm) = @_;
    my ($frame);

    $gConfigDlg = $wm->Toplevel(-title => 'Configuring SyncTime');
    $gConfigDlg->transient($wm);

    $gConfigDlg->Label(-text =>
	"SyncTime v$VERSION       Alan Harder")->pack;

    $frame = $gConfigDlg->Frame(-relief => 'ridge', -bd => 3);
    $frame->Label(-text => "Set Pilot Time:")->pack;
    TkUtils::Radiobuttons($frame, \$PREFS->{'howOften'},
			  'Every Sync', 'Daily', 'Weekly', 'Monthly');
    $frame->pack;

    $gConfigDlg->Label(-text =>
	"SyncTime copies your desktop time to the pilot,\n" .
	"so keep your desktop time accurate.\n" .
	"Thanks to Chris Ice for the idea!")->pack;

    $gConfigDlg->Button(-text => 'Dismiss', -command =>
	['withdraw', $gConfigDlg])->pack;

    PilotMgr::setColors($gConfigDlg);
}

sub conduitSync
{
    my ($this, $dlp, $info) = @_;

    if (&timeToUpdate)
    {
	$PREFS->{'lastTime'} = time;
	PilotMgr::msg('Setting time on pilot..');
	$dlp->setTime(time);
    }
}

sub loadPrefs
{
    $PREFS = {}, return unless (-r "$RCFILE");
    do "$RCFILE";
}

sub savePrefs
{
    $Data::Dumper::Purity = 1;
    $Data::Dumper::Deepcopy = 1;
    $Data::Dumper::Indent = 0;

    if (open(FD, ">$RCFILE"))
    {
	print FD Data::Dumper->Dumpxs([$PREFS], ['PREFS']);
	print FD "1;\n";
	close(FD);
    }
    else
    {
	PilotMgr::msg("Unable to save preferences to $RCFILE!");
    }
}

sub timeToUpdate
{
    my (@lst, @now, $dif);

    @lst = localtime($PREFS->{'lastTime'});
    @now = localtime(time);
    $dif = time - $PREFS->{'lastTime'};

    if ($PREFS->{'howOften'} eq 'Every Sync'				  or

	$PREFS->{'howOften'} eq 'Daily' &&
	 ($lst[3] != $now[3]  or  $dif >= 86400)			  or

	$PREFS->{'howOften'} eq 'Weekly' &&
	 ($lst[6] > $now[6]  or  $dif >= 604800  or
	  ($lst[6] == $now[6] and $dif > 86400))			  or

	$PREFS->{'howOften'} eq 'Monthly' &&
	 ($lst[4] != $now[4]  or  $dif >= 18748800)
	)
    {
	return 1;
    }

    return 0;
}

1;

