import os, sys, string, time
from Ft.Ods import Database
from xml.dom.ext.reader import Sax
from xml.dom import Node
#User object class
from BookmarkManager import Bookmark

def Import(xbel_file, db_name):
    print "Create DB", time.time()
    db = Database.Database()
    print "Open DB", time.time()
    db.open(db_name)

    tx = db.new()
    tx.begin()

    print "Begin processing", time.time()
    xbel = Sax.FromXmlFile(xbel_file)
    ProcessNode(xbel.documentElement, db, [])

    print "Commit", time.time()
    tx.commit()
    print "Close", time.time()
    db.close()
    print "Done", time.time()
    return

def ProcessNode(node, db, currCategories):
    if node.nodeType == Node.ELEMENT_NODE:
        if node.nodeName == 'folder':
            ProcessFolder(node, db, currCategories)
        elif node.nodeName == 'bookmark':
            ProcessBookmark(node, db, currCategories)
        elif node.nodeName == 'xbel':
            ProcessFolder(node, db, currCategories)

def ProcessFolder(node, db, currCategories):
    title = ''
    for child in node.childNodes:
        if node.nodeType == Node.ELEMENT_NODE:
            if child.nodeName == 'folder':
                ProcessFolder(child, db, currCategories)
            elif child.nodeName == 'title':
                currCategories.append(child.firstChild.data)
            elif child.nodeName == 'bookmark':
                ProcessBookmark(child, db, currCategories)

def ProcessBookmark(node, db, currCategories):
    url = node.getAttribute('href')
    desc = node.childNodes[1].firstChild.data

    bm = Bookmark.new(db)
    bm.url = url
    bm.description = desc
    for c in currCategories:
        bm.categories.insert_element(c)

    return


if __name__ == "__main__":
    Import(sys.argv[1], sys.argv[2])

