#! /usr/bin/env python
# Converts from gajim's log db to gaim format and pops it into gaim with
# USER_NAME as the user id.
import os
import sys
import time
import datetime

SECONDS_IN_A_DAY=86400 # 60*60*24
LOG_PATH = os.path.expanduser("~/.gajim/logs.db")
GAIM_LOG_DIR = os.path.expanduser("~/.gaim/logs/")
USER_NAME = "whatah"

(
        KIND_STATUS,
        KIND_GCSTATUS,
        KIND_GC_MSG,
        KIND_SINGLE_MSG_RECV,
        KIND_CHAT_MSG_RECV,
        KIND_SINGLE_MSG_SENT,
        KIND_CHAT_MSG_SENT,
        KIND_ERROR
) = range(8)

try:
	import sqlite3 as sqlite # python 2.5
except ImportError:
	try:
		from pysqlite2 import dbapi2 as sqlite
	except ImportError:
		raise exceptions.PysqliteNotAvailable

# Get the day based on seconds.
def getDayInSeconds(seconds):
    return time.mktime(datetime.date.fromtimestamp(seconds).timetuple())

def getSecondsFromDay(day):
    return time.mktime(day.timetuple())
def getDay(seconds):
    return datetime.date.fromtimestamp(seconds)

def getDayTime(seconds):
    return datetime.datetime.fromtimestamp(seconds)

def getTime(seconds):
    return datetime.datetime.fromtimestamp(seconds).strftime("(%I:%M:%S %p)")

def generateLogs(earliest=None):
    dbcon = sqlite.connect(LOG_PATH)
    cursor = dbcon.cursor()
    jid_to_id = {}
    id_to_jid = {}

    # Get all JIDs
    cursor.execute("SELECT jid, jid_id FROM jids")
    rows = cursor.fetchall()
    for row in rows:
        jid = row[0].encode("utf-8")
        id = str(row[1]).encode("utf-8")
        jid_to_id[jid] = id
        id_to_jid[id] = jid

    # Build our log directory hierarchy
    try:
        os.makedirs("%s/gajim/%s"%(GAIM_LOG_DIR, USER_NAME))
    except OSError, e:
        pass

    # Now we go through each JID and build the conversation for them, day by day.
    if not earliest:
        cursor.execute("SELECT time FROM logs ORDER BY time")
        rows = cursor.fetchone()
        earliest = rows[0]

    start_time = getDayInSeconds(earliest)
    end_time = start_time + SECONDS_IN_A_DAY - 1
    today = getDayInSeconds(time.time())
    while start_time <= today:
        # Find all conversations that happened on this day.
        day = getDay(start_time)
        for jid in jid_to_id:
            id = jid_to_id[jid]
            cmd = "SELECT message, time, kind, contact_name FROM logs WHERE jid_id = %s AND time BETWEEN %s AND %s ORDER BY time" % (id, start_time, end_time)
            cursor.execute(cmd)
            rows = cursor.fetchall()
            if not rows:
                continue
            # Create the directory for this user, so we don't clutter.
            try:
                os.makedirs("%s/gajim/%s/%s"%(GAIM_LOG_DIR, USER_NAME, jid))
            except OSError, e:
                pass
            # Should the conversation started business be implemented?
            # Conversation with apparentlynew at Mon 04 Dec 2006 06:16:13 PM EST on purjenikartofi (aim)      
            earliest = rows[0][1] # earliest time.
            timestamp = getDayTime(earliest).strftime("%H%M%S")
            filename = "%s/gajim/%s/%s/%s.%s.txt" % (GAIM_LOG_DIR, USER_NAME, jid, day, timestamp)
            log_file = open(filename, "w")
            print filename
            for row in rows:
                message, msg_time, kind, contact_name = row
                msg_time = getTime(msg_time)
                if contact_name:
                    sender = unicode(contact_name.encode("utf-8"), errors='ignore')
                elif kind in (KIND_SINGLE_MSG_RECV, KIND_CHAT_MSG_RECV, KIND_GC_MSG):
                    sender = unicode(jid, errors='ignore')
                elif kind in (KIND_SINGLE_MSG_SENT, KIND_CHAT_MSG_SENT):
                    sender = USER_NAME
                message = unicode(message.encode("utf-8"), errors='ignore')
                print >> log_file, "%s %s: %s" % (msg_time, sender, message)
#                print "%s %s: %s" % (msg_time, sender, message)

        start_time += SECONDS_IN_A_DAY
        end_time += SECONDS_IN_A_DAY
    day = getDay(today)
    # Record the day
    date_file = open(os.path.expanduser("~/.gajim/gajim2gaim.txt"), "w")
    print >> date_file, day

import optparse
if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-d", "--day", dest="day",
                  action="store", type="str", help="generate logs from DAY to \
                  today days ago to today (DAY is in YYYY-MM-DD format", metavar="DAY")
    parser.add_option("-n", "--numdays", dest="days",
                  action="store", type="int", help="generate logs from n days ago to today", metavar="DAYS")
    options, args = parser.parse_args(sys.argv) 
    if options.day:
        opts = options.day.split('-')
        if len(opts) != 3:
            print "Invalid date format (%s)" % (options.day)
        else:
            opts = map(int, opts)
            seconds = getSecondsFromDay(datetime.date(opts[0], opts[1], opts[2]))
            generateLogs(seconds)
    elif options.days or options.days == 0:
        generateLogs(time.time() - options.days*SECONDS_IN_A_DAY)
    else:
        generateLogs()
# vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79:

