#! /usr/bin/python
# -*- coding: UTF-8 -*-

__license__ = """
Copyright (c) 2006 Satoru SATOH <ss@gnome.gr.jp>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

__version__ = "0.1"

from pysqlite2 import dbapi2 as sqlite
import re
import string
import sys

def convert (src, dst):
	import cjkcodecs
	def s2u(s): return unicode(s,'cjkcodecs.cp932').encode('utf-8')
	try: 
		f=open(dst, "w")
		i=0
		for l in open(src, "r").readlines():
			i += 1
			try: l = s2u(l)
			except:
				sys.stderr.write("Conversion error: #%d\n" % int(i))
				continue
			f.write(l)
		f.close()
	except:
		sys.stderr.write("Unable to open %s\n" % src)
		sys.exit(1)

# e.g.
# ■$1 store : ...
# ■.38  {名} : 38口径｛こうけい｝ピストル
# ■A. Turing  {人名} : ＝<→Alan M. Turing>
# ■a.m. : 【発音】e'ie'm
# ■-altering  {連結} : 〜を変える■・Authorities ... drug.■・He was... 
REG = re.compile(r"^■(?P<key>[^:{]+)(?:  {(?P<type>[^ :]+)})*" +
	r" : (?:《(?P<category>[^》]+)》)*(?P<description>[\S\s]+)")

CREATETABLE_SQL = """
CREATE TABLE IF NOT EXISTS eijiro (
	word text NOT NULL,
	description text NOT NULL,
	type text NOT NULL DEFAULT na,
	category text NOT NULL DEFAULT na
)
"""
INSERT_SQL = "INSERT INTO eijiro (word,description,type,category) VALUES(?, ?, ?, ?)"

# SQLite v 3.3.3 or later:
try: sqlite.enable_shared_cache(True)
except: pass

def entryGenerator(f):
	for l in f.readlines():
		m = re.match(REG, string.rstrip(l))
		if m is not None:
			key,description = m.group('key'),m.group('description')
			type,category = m.group('type'),m.group('category')

			# FIXME: Any other appropriate default values?
			if type is None: type = 'na'
			if category is None: category = 'na'

			sys.stderr.write("%s, %s, %s, %s\n" % (key,description,type,category))
			yield(key,description,type,category)

def exit_on_error(x, message=None):
	if message is None: message = "Cannot open %s to parse. Aborting...\n"
	sys.stderr.write(message % x)
	sys.exit(1)

def create(src="eijiro.txt", dst="eijiro.db"):
	try: f = open(src, "r")
	except: exit_on_error(src)
	
	try: con = sqlite.connect(dst, isolation_level=None)
	except: exit_on_error(dst)

	cur = con.cursor()
	cur.execute(CREATETABLE_SQL)
	#for xs in entryGenerator(f): cur.execute(INSERT_SQL, xs)
	cur.executemany(INSERT_SQL, entryGenerator(f))
	con.commit()
	con.close()

def search(key, perfect=False, db="eijiro.db"):
	try: con = sqlite.connect(db)
	except: exit_on_error(db)

	sql = "SELECT word,description FROM eijiro WHERE word "
	if perfect: sql += "= '%s'" % key
	else: sql += "LIKE '" + key + "%'"

	cur = con.cursor()
	cur.execute(sql)
	rs = cur.fetchall()
	con.close()
	return rs

if __name__ == '__main__':
	def usage (exit_code = 0):
		this = sys.argv[0]
		print """
Usage: %s [OPTIONS]
Options:
  -h, --help	display this help and exit
  -p, --perfect	Search a perfect match
  -d, --db=DB	Database to search [Default=eijiro.db]
""" % sys.argv[0]
		sys.exit(exit_code)

	def do_search(key, perfect, db):
		rs = search(key, perfect, db)
		u2u = lambda s: unicode(s).encode('utf-8')
		if perfect:
			sys.stdout.write("%s =\n" % key)
			for r in rs: sys.stdout.write(u2u("%s\n" % r[1]))
		else:
			for r in rs: sys.stdout.write(u2u("%s = %s\n" % r))

	def main():
		import getopt
		perfect, db = False, "eijiro.db"
		try:
			opts, args = getopt.getopt(sys.argv[1:],
				"hpd:", ["help", "perfect", "db"]
			)
			for opt, arg in opts:
				if opt in ("-h", "--help"): usage()
				if opt in ("-p", "--perfect"): perfect = True
				if opt in ("-d", "--db"): db = arg
		except getopt.error, msg: usage(2)
		if len(sys.argv) < 2: usage(2)

		do_search(sys.argv[-1], perfect, db)

	main()

