#!/usr/bin/python
"""pydic --Character Based NDTP Client--

  Author: tgz <tgz@users.sourceforge.jp>
  Version: 1.2
  Last Modified: 2004/01/19

  This program is based on GPL.

"""
import os, re, readline, sys
import string
from ndtplib import *

class PyDic:
    def __init__(self, server):
        """Get Version and Dictionaries of Server."""
        self.name = 'pydic'
        self.version = '1.2'
        self.Info, self.Eh, self.Bye, self.Chng = (':v', ':h', ':q', ':l')
        self.NDTP = NDTP(server)
        self.dictdict = self.NDTP.listdic()
        self.DEFAULTDICNUM_LIST = self.dictdict.keys()
        self.dicnum_list = self.DEFAULTDICNUM_LIST
        self.dicnum_list.sort()
        self.NDTP.quit()
        self.info()
        self.help()

    def info(self):
        print 'n%s version %s --Character Based NDTP Client--\n' % \
(self.name, self.version)

    def help(self):
        """Show Commands."""
        usage = {self.Info: 'About This Program',
                  self.Eh: 'Show Commands(This Message)',
                 self.Bye: 'Quit'}
                #self.Chng: 'Change Dictionary'}
        print '\nCommands:'
        keys = usage.keys()
        keys.sort()
        for i in keys:
            print '\t%s\t%s' % (i, usage[i])
        print '\nAny words are regarded as query except for the above \
commands.\n'

    def browse(self, command):
        """Browse Results."""
        pid = os.fork()
        if pid != 0:
            """Parent process"""
            os.wait()
        else:
            """Child process"""
            num = ''
            for dicnum in self.dicnum_list:
                num = num + '%s,' % (dicnum)
            num = num[:-1]
            os.system(self.search(command, num))
            os._exit(1)
        return pid

    def search(self, pattern, dicnum):
        """Search Pattern."""
        NDTP_HOST = '127.0.0.1'
        pager  = '/usr/bin/w3m'
        return '%s \'file:///cgi-bin/pydicfunc.cgi?server=%s&num=%s&word=%s\'' % \
(pager, NDTP_HOST, dicnum, pattern)

def search(pattern, dicnum):
    """Search Pattern."""
    NDTP_HOST = '127.0.0.1'
    pager  = '/usr/bin/w3m'
    return '%s \'file:///cgi-bin/pydicfunc.cgi?server=%s&num=%s&word=%s\'' % \
(pager, NDTP_HOST, dicnum, pattern)

def main():
    """main loop"""
    NDTP_HOST = '127.0.0.1'
    file = pid = None
    n = PyDic(NDTP_HOST)
    version, dictdict = n.version, n.dictdict
    prompt = '[%s]$ ' % n.name
    COND = 1
    while COND:
        cmd = raw_input(prompt)
        if cmd == '' or re.match('^[ ]+$', cmd):
            pass
        elif cmd == n.Bye:
            sys.exit(1)
        #elif cmd == n.Chng:
        #    n.selectdic()
        elif cmd == n.Eh:
            n.help()
        elif cmd == n.Info:
            n.info()
        else:
            try:
                pid = n.browse(cmd)
                COND = 1
            except Exception, message:
                print message
                pass

if __name__ == '__main__':
    try:
        main()
    except NDTPServerDisconnected, message:
        print message
        sys.exit(1)
    except (EOFError, KeyboardInterrupt):
        sys.exit(1)
