"""
Find Contact and Query Birthdays
"""
#  Copyright (C) 2004  Henning Jacobs <henning@srcco.de>
#
#  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.
#
#  $Id: Query.py 82 2004-07-11 13:01:44Z henning $

import vcard
import Pmw
import MultiColumnTextList
from Tkinter import *
import time
import debug

# Max number of tel/emails/adrs to be searched through:
MAX_N_SEARCH_FIELDS = 5

last_searchdef = None
def FindContact(master, model, start=None, searchnext=0):
    global last_searchdef
    import FindDialog
    import re
    if (not searchnext) or (not last_searchdef):
        dlg = FindDialog.FindDialog(master)
        if dlg.activate() == 'Ok':
            searchdef = dlg.getvalue()
        else:
            return None
    else:
        searchdef = last_searchdef
    searchstr, fieldname, useregex, ignorecase = searchdef
    handles = model.ListHandles()
    if start:
        pos = handles.index(start)
        if pos < len(handles)-1:
            pos += 1
        else:
            # Restart Search at First Contact:
            pos = 0
    else: 
        pos = 0
    # Tk deals with UTF-8 strings, but we want Unicode:
    searchstr = unicode(searchstr, 'utf-8', 'replace')
    regex_flags = None
    if ignorecase:
        searchstr = searchstr.lower()
        regex_flags = re.IGNORECASE
    for handle in handles[pos:]+handles[:pos]:
        # Search in max. MAX_N_SEARCH_FIELDS fields of the same name:
        vals = model.QueryAttributes([handle], [fieldname]*MAX_N_SEARCH_FIELDS)
        for val in filter(None, vals[0]):
            if useregex:
                # The User wants to Use Regular Expressions:
                if re.search(searchstr, val, regex_flags):
                    last_searchdef = searchdef
                    return handle
            else:
                # Standard String Search:
                if ignorecase:
                    val = val.lower()
                if val.find(searchstr) <> -1:
                    last_searchdef = searchdef
                    return handle

def Birthdays(master, model):
    attrlist = model.QueryAttributes(model.ListHandles(), ('FormattedName','Birthday'))
    bdays = []
    for fn, bday in attrlist:
        if bday:
            isodate = bday
            year = int(isodate[:4])
            month = int(isodate[5:7])
            day = int(isodate[8:])
            curtime = time.localtime()
            curyear = curtime[0]
            curmonth = curtime[1]
            curday = curtime[2]
            if month > curmonth or (month == curmonth and day >= curday):
                y = curyear
            else:
                y = curyear+1
            secs = time.mktime((y, month, day, 0, 0, 0, 0, 1, -1))
            sortidx = secs - time.time()
            tuple = (sortidx, year, month, day, fn, y)
            bdays.append(tuple)
    bdays.sort()
    #text = ""
    rows = []
    for bday in bdays:
        no = str(bday[5]-bday[1])
        if no[-1:] == "1":
            ext = "st"
        elif no[-1:] == "2":
            ext = "nd"
        elif no[-1:] == "3":
            ext = "rd"
        else: 
            ext = "th"
        no = no+ext
        rows.append(("%(y)04d-%(m)02d-%(d)02d" % {
            "y":bday[5],
            "m":bday[2],
            "d":bday[3]}, "%(no)s Birthday of %(name)s" % {
            "name":bday[4],
            "no":no}))      
    dlg = Pmw.Dialog(master, title="Birthdays",
        buttons=('Close',), defaultbutton='Close')
    dlg.withdraw()
    textlist = MultiColumnTextList.MultiColumnTextList(dlg.interior(), autocolresize=0)
    textlist.setcolwidthsfromstr(['2004-12-31','Birthday'])
    textlist.pack(fill=BOTH, expand=1)
    for row in rows:
        textlist.append(row)
    dlg.show()

