import contacts
import calendar
import time
import globalui
import sys

#
# A script to update the calendar using the contact birthdays
#
# For each contact, check if a date ('Birthday') is present.
# If so, check if an existing anniversary exists for this contact.
# If not, add a new anniversary on this contact's birthday,
# repeating every year.
#
# Copyright (c) 2008 Alex de Landgraaf
#
# Fix for unicode characters in names, 28/02/2009, Markus Dobel
#
# License: Feel free to do with this as you please.
#

year = 365 * 24 * 60 * 60
week = 7 * 24 * 60 * 60

ret = globalui.global_query(u"Ready to copy over contact birthdays to your calendar. Proceed?")
if ret == 0:
    sys.exit()

max_timestamp = 2143234800.0 # 1/12/2037. Nokia doesn't think we'll need birthdays after 2037 (ie. it uses timestamps for dates)

calendar_db = calendar.open()
contact_db = contacts.open()
keys = contact_db.keys()

for k in keys:
    contact = contact_db[k]
    for field in contact:
        if field.type == 'date': # Assume all dates in contacts are birthdates
            date = field.value
            name = contact.title
            print u"Checking anniversary for " + unicode(name)
            existing_instances = calendar_db.find_instances(start_date = date - week, end_date = date + week, search_string = contact.title)
            if len(existing_instances) > 0:
                print("Found existing anniversary")
            else:
                print("No existing anniversary found. Adding new.")
                ann_entry = calendar_db.add_anniversary()
                ann_entry.set_time(date)
                ann_entry.content = name
                repeat = {"type": "yearly_by_date",
                          "start": ann_entry.start_time, # Start at birthdate
                          "end": max_timestamp, # Continue for a couple of years
                          "interval": 1} # Repeat every year
                ann_entry.set_repeat(repeat)
                ann_entry.commit()
            print u"Evaluated anniversary for " + unicode(name)
            print()
print("All done!")
globalui.global_query(u"Your calendar has been updated using the contact birthdays!\ncheers, Alex de Landgraaf (www.alextreme.org)")
