#! /usr/bin/perl
#
# Copyright (c) 2007 Olaf Dietsche
# Version: 0.1
#
# Converts a Palm ToDoDB.pdb to an Emacs Orgmode todo list. This perl
# script needs the p5-Palm package, which is available at:
# <http://www.coldsync.org/>.
#
# If you use debian, you may install the libpalm-perl Package
# available at: <http://packages.debian.org/libpalm-perl>

use strict;
use warnings;

use Palm::PDB;
use Palm::StdAppInfo;
use Palm::ToDo;

use Getopt::Long;

my $help;
my $heading = "* Todo";
my $rc = GetOptions("heading=s" => \$heading,
		    "noheading" => sub { $heading = ''; },
		    "help|?" => \$help,
		   );

if (!$rc || $help || $#ARGV < 0) {
	print STDERR "usage: $0 [--noheading] [--heading='* Todo'] ToDoDB.pdb\n";
	exit(2);
}

sub dump_record
{
	my($pdb, $record) = @_;
	my $done = $record->{completed} ? "DONE" : "TODO";
	print "** $done";

	my $priority = $record->{priority};
	my $prio;
	$prio = "A" if ($priority <= 1);
	$prio = "C" if ($priority >= 3);

	print " [#$prio]" if ($prio);

	my $desc = $record->{description};
	print " $desc";

	my $date;
	if (defined($record->{due_day})) {
		$date = sprintf("<%04d-%02d-%02d>", $record->{due_year}, $record->{due_month}, $record->{due_day});
	}

	print " $date" if ($date);
	print "\n";

	my $note = $record->{note};
	print "$note" if ($note);
}

my $pdb = new Palm::PDB;

print "$heading\n" if ($heading);

for my $f (@ARGV) {
	$pdb->Load($f);
	my $records = $pdb->{records};
	for (@{$records}) {
		print "\n";
		dump_record($pdb, $_);
	}
}
