%Converts Palm(R) DateBook(TM) database files into Emacs Diary files.
%Copyright (C) 2006  Romain Lenglet <rlenglet@users.forge.objectweb.org>
%
%This program is free software; you can redistribute it and/or
%modify it under the terms of the GNU General Public License
%as published by the Free Software Foundation; either version 2
%of the License, or (at your option) any later version.
%
%This program is distributed in the hope that it will be useful,
%but WITHOUT ANY WARRANTY; without even the implied warranty of
%MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%GNU General Public License for more details.
%
%You should have received a copy of the GNU General Public License
%along with this program; if not, write to the Free Software
%Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

-module(palm_datebook_to_diary).
-version(0.1). % 2006-09-06

% To execute this program, run:
% erl -noshell -run palm_datebook_to_diary start <db_file> -run init stop > <diary_file>

-export([start/1]).

-include("palm_db.hrl").

% Exported functions:

start([Filename]) ->
    {_DatabaseHdr, Records} = palm_db:read_datebook_db(Filename),
    display_datebook_records(Records).

% Function to display DateBook records in Emacs Diary format:

display_datebook_records([]) ->
    ok;
display_datebook_records([Record|Tail]) ->
    io:format("~s ~s ~s~n", [date_to_string(Record#datebook_record.start_date),
			     time_to_string(Record#datebook_record.start_time),
			     Record#datebook_record.description]),
    % FIXME: end time!
    Note = Record#datebook_record.note,
    if
	Note /= [] ->
	    io:format("\t~s~n", [indent_note(Note)]);
	true ->
	    ok
    end,
    display_datebook_records(Tail).

time_to_string(Time) ->
    #datebook_time{hour = Hour, minute = Minute} = Time,
    if
	(Hour > 24) or (Minute > 60) ->
	    "";
	true ->
	    HourStr = integer_to_list(Hour),
	    MinuteStr = integer_to_list(Minute),
	    case length(HourStr) of
		1 -> "0" ++ HourStr;
		2 -> HourStr
	    end
            ++ ":" ++
	    case length(MinuteStr) of
		1 -> "0" ++ MinuteStr;
		2 -> MinuteStr
	    end
    end.

date_to_string(Date) ->
    #datebook_date{year = Year, month = Month, day = Day} = Date,
    month_to_string(Month)
	++ " " ++ integer_to_list(Day)
	++ ", " ++ integer_to_list(Year).

month_to_string(1) -> "January";
month_to_string(2) -> "February";
month_to_string(3) -> "March";
month_to_string(4) -> "April";
month_to_string(5) -> "May";
month_to_string(6) -> "June";
month_to_string(7) -> "July";
month_to_string(8) -> "August";
month_to_string(9) -> "September";
month_to_string(10) -> "October";
month_to_string(11) -> "November";
month_to_string(12) -> "December".

indent_note([]) ->
    [];
indent_note([$\n|Tail]) ->
    ["\n\t" | indent_note(Tail)];
indent_note([AnyChar|Tail]) ->
    [AnyChar | indent_note(Tail)].
