#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This script shouldbe migrated with py-transport2spectrum in the future.
import os,  os.path, sys
try:
        import MySQLdb
except:
    print "MySQLdb is not installed"
try:
        import sqlite3
except:
        print "sqlite3 is not installed"

from twisted.web import microdom as dom
from twisted.web.domhelpers import *


def start():
	if len(sys.argv) != 6 and len(sys.argv) != 7 and len(sys.argv) != 3 and len(sys.argv) != 4:
			print "Usage for MySQL: " + sys.argv[0] + " transport_path database username password host [mysql_prefix]"
			print "Usage for SQLite: " + sys.argv[0] + " transport_path database [prefix]"
			return
	maindir = sys.argv[1]
	files = os.listdir(maindir)

	prefix = ""
	if len(sys.argv) == 7:
			prefix = sys.argv[6]
	elif len(sys.argv) == 4:
			prefix = sys.argv[3]
	if len(sys.argv) == 3 or len(sys.argv) == 4:
			if not os.path.exists(sys.argv[2]):
					print "Run Spectrum to create this DB file first and then run this script again with the DB file created by Spectrum."
					return
			db = sqlite3.connect(sys.argv[2])
	else:
			db = MySQLdb.connect(host=sys.argv[5], user=sys.argv[3], passwd=sys.argv[4], db=sys.argv[2])
	cursor = db.cursor()
	c = 0
	size = len(files)
	for f in files:
			if os.path.isfile(maindir + "/" + f) and not f in ['pubsub', 'avatars']:
					c += 1
					print "[" + str(c) + "/" + str(size) + "] " + f
					fp = open(maindir + "/" + f, 'r')

					buff = fp.read()
					fp.close()
					try:
							x = dom.parseXMLString(buff)
					except:
							print "Can't parse", f, ". Skipping..."
							continue
					jid = os.path.basename(f).replace('%','@')
					p = x.getElementsByTagName('password')
					if len(p) != 1:
							print "No password for jid", jid, ". Skipping..."
							continue
					password =  gatherTextNodes(p[0])
					u = x.getElementsByTagName('uin')
					uin = gatherTextNodes(u[0])

					if len(sys.argv) == 3 or len(sys.argv) == 4:
							cursor.execute('insert or ignore into ' + prefix + 'users (jid, uin, password, language) values (?, ?, ?, "en")', (jid, uin, password))
					else:
							cursor.execute('insert ignore into ' + prefix + 'users (jid, uin, password, language) values (%s, %s, %s, "en")', (jid, uin, password))
					if len(sys.argv) == 3 or len(sys.argv) == 4:
							cursor.execute('select id from ' + prefix + 'users WHERE jid = "'+jid+'"')
					else:
							cursor.execute('select id from ' + prefix + 'users WHERE jid = %s', (jid))
					row = cursor.fetchone()
					user_id = int(row[0])

					items = x.getElementsByTagName('contact')
					for j in items:
							if len(sys.argv) == 3 or len(sys.argv) == 4:
									cursor.execute('insert or ignore into ' + prefix + 'buddies (uin, user_id, nickname, groups, subscription) values (?, ?, ?,"Buddies", "both")',(j.getAttribute('uin'), str(user_id), j.getAttribute('uin')))
							else:
									cursor.execute('insert ignore into ' + prefix + 'buddies (uin, user_id, nickname, groups, subscription) values (%s, %s, %s,"Buddies", "both")',(j.getAttribute('uin'), str(user_id), j.getAttribute('uin')))
	db.commit()
	cursor.close()
	db.close()
	#print "Everything done!"
	#reactor.stop()

start()
