"""
Converts Palm address book files (address.dat or *.aba) to vCard format

Requires palmFile module available from
  http://www.totic.org/develop/palmFile.py

See also:
  http://www.geocities.com/Heartland/Acres/3216/
  http://www.imc.org/pdi/pdiproddev.html
"""

"""
Author: Paul Eggleton (bluelightning@bluelightning.org)

Version 0.1
Date: 2004-12-08
    Initial version. Converts all fields, but does not handle categories 
    and possibly doesn't give proper label to some telephone number types.
"""

"""
Copyright (c) 2004 Paul Eggleton

This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.

    2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.

    3. This notice may not be removed or altered from any source distribution.
"""

def phoneLabelIDToVCardLine(labelid, phonetext, preferred):
    if preferred:
      preftext = ";PREF"
    else:
      preftext = ""

    if labelid == 0L:
        return "TEL;WORK" + preftext + ":" + phonetext
    elif labelid == 1L:
        return "TEL;HOME" + preftext + ":" + phonetext
    elif labelid == 2L:
        return "TEL;WORK;FAX" + preftext + ":" + phonetext
    elif labelid == 3L:
        if phonetext[0:4] == "http":
            return "URL:" + phonetext
        else:
            return "TEL" + preftext + ":" + phonetext
    elif labelid == 4L:
        return "EMAIL;INTERNET:" + phonetext
    elif labelid == 6L:
        return "TEL;PAGER" + preftext + ":" + phonetext
    elif labelid == 7L:
        return "TEL;CELL" + preftext + ":" + phonetext
    else:
        return "TEL" + preftext + ":" + phonetext

def addressToVCardLine(address):
    import string
    street = string.replace(address["address"],"\r","")
    street = string.replace(street,"\n","\\n")
    addrline = "ADR;WORK:;;" + street + ";" + address["city"] + ";" + address["state"] + ";" + address["zip"] + ";" + address["country"]
    return addrline
    
def foldFormattedString(textvalue):
    import string
    noteline = string.replace(textvalue,"\r","")
    noteline = string.replace(noteline,"\n","\\n")
    return noteline

def printvcards(adBook, custom1field, custom2field, custom3field, custom4field):
    addressDict = adBook[0]
    addresses = addressDict["addresses"]
    for address in addresses:
        print "BEGIN:VCARD"
        print "VERSION:2.1"
        print "FN:" + address["firstName"] + " " + address["lastName"]
        print "N:" + address["lastName"] + ';' + address["firstName"]
        displayPhone = address["displayPhone"]
        if address["title"] != "":
            print "ROLE:" + address["title"]
        if address["companyName"] != "":
            print "ORG:" + address["companyName"]
        if address["phone1Text"] != "":
            print phoneLabelIDToVCardLine(address["phone1LabelID"], address["phone1Text"], displayPhone == 1L)
        if address["phone2Text"] != "":
            print phoneLabelIDToVCardLine(address["phone2LabelID"], address["phone2Text"], displayPhone == 2L)
        if address["phone3Text"] != "":
            print phoneLabelIDToVCardLine(address["phone3LabelID"], address["phone3Text"], displayPhone == 3L)
        if address["phone4Text"] != "":
            print phoneLabelIDToVCardLine(address["phone4LabelID"], address["phone4Text"], displayPhone == 4L)
        if address["phone5Text"] != "":
            print phoneLabelIDToVCardLine(address["phone5LabelID"], address["phone5Text"], displayPhone == 5L)
        if address["address"] != "":
            print addressToVCardLine(address)
        if address["note"] != "":
            print "NOTE:" + foldFormattedString(address["note"])
        if address["custom1Text"] != "":
            print custom1field + ":" + address["custom1Text"]
        if address["custom2Text"] != "":
            print custom2field + ":" + address["custom2Text"]
        if address["custom3Text"] != "":
            print custom3field + ":" + address["custom3Text"]
        if address["custom4Text"] != "":
            print custom4field + ":" + address["custom4Text"]
        print "END:VCARD"
    return


if __name__ == "__main__":
    import sys
    import getopt
    import palmFile
    try:
        options, args = getopt.getopt(sys.argv[1:], '1:2:3:4:')
        custom1field = "X-CUSTOM1"
        custom2field = "X-CUSTOM2"
        custom3field = "X-CUSTOM3"
        custom4field = "X-CUSTOM4"
        
        for o, a in options:
            if o == "-1":
               custom1field = a
            elif o == "-2":
               custom2field = a
            elif o == "-3":
               custom3field = a
            elif o == "-4":
               custom4field = a
        
        fileToRead = args[0]

    except:
        print "palm2vcard 0.1"
        print "Converts Palm address book (address.dat or *.aba) to vCard format on stdout"
        print "Usage: python palm2vcard.py [options] <addressfile>"
        print " -1 specify vCard field to map custom 1 text to (default X-CUSTOM1)"
        print " -2 specify vCard field to map custom 2 text to (default X-CUSTOM2)"
        print " -3 specify vCard field to map custom 3 text to (default X-CUSTOM3)"
        print " -4 specify vCard field to map custom 4 text to (default X-CUSTOM4)"
        exit(-1)

    palmData = palmFile.readPalmFile(fileToRead)

    isaddressbook = (palmData[0]["versionTag"] == 1094844672L) # addresses

    if isaddressbook:
        printvcards(palmData, custom1field, custom2field, custom3field, custom4field)
    else:
        print "error: format not recognised or not a Palm address book file"
