#----------------------------------------------------------------------
# POO help module                    Trevor Clarke    8/09/96
#                                    last update: JJS 8/10/96
#----------------------------------------------------------------------
import pickle
import string

helpDB={}

class HelpRec:
	def __init__(self):
		self.syntax = ''		# one-line syntax summary
		self.desc = ''			# long description
		self.initial = 0		# if 1, appears in initial "topics" list
	
	def show(self):
		if self.syntax:
			return "Syntax: " + self.syntax + "\n" + self.desc + "\n\n"
		else:
			return self.desc + "\n\n"

	def enter(self):
		self.syntax = raw_input("Enter syntax string: ")
		print "Enter help message, period(.) alone to end:"
		print "------------------------------------------"
		done=0
		self.desc=""
		while not done:
			tex = raw_input()
			if tex==".": done = 1
			else: self.desc = self.desc+"\n"+tex
		ans = raw_input("Show on initial topics list? ")
		self.initial = (ans[0]=='y' or ans[0]=='Y' or ans[0]=='1')

def hSave(filename='poohelp.dat'):
	global helpDB
	file = open(filename, 'w')
	pickle.dump(helpDB, file)
	file.close()

def hLoad(filename='poohelp.dat'):
	global helpDB
	file = open(filename, 'r')
	helpDB = pickle.load(file)
	file.close()

def new():
	global helpDB
	return "Creating empty help database..."
	helpDB = {}

def help(topic=None):
	global helpDB
	if not topic:
		output = "Available help topics:\n\n"
		lst = filter(lambda x:helpDB[x].initial, helpDB.keys())
		lst.sort()
		for topic in lst:
			output = output + "   "+ topic + "\n"
		return output + "\n"
	else:
		try:
			return helpDB[topic].show()
		except:
			# if no exact match is found, what about a partial match?
			lst = filter(lambda x,a=topic,l=len(topic): x[:l]==a,helpDB.keys())
			if not (lst): 
				if (topic[:3] == "at_"):
					return help( "@" + topic[3:] )
				return "No help available on "+topic+".\n"
			if len(lst) > 1:
				return "Ambiguous topic:\n   " + string.join(lst,'\n   ')+'\n'
			return helpDB[lst[0]].show()

def addTopic(topic):
	global helpDB
	hr = HelpRec()
	hr.enter()
	helpDB[topic] = hr

def deleteTopic(topic):
	global helpDB
	try: del helpDB[topic]
	except: print "Couldn't delete topic",topic

def popDB():
	done = 0
	while not done:
		foo = raw_input("help>")
		cmd = foo[:2]
		if cmd == ".q": done = 1
		elif cmd == ".s": hSave()
		elif cmd == ".l": hLoad()
		elif cmd == ".n": new()
		elif cmd == ".h" or cmd == ".d":
			try: foo = string.split(foo)[1]
			except: foo = ''
			if not foo: foo = raw_input("topic>")
			if cmd == ".h": print help(foo)
			elif cmd==".d": deleteTopic(foo)
		elif cmd == ".?":
			print "Enter one of:"
			print "   .quit  .save   .load   .new   .help   .del"
			print "(Commands may be abbreviated to the first letter.)"
		elif cmd == ".": pass
		elif cmd == "": pass
		else: addTopic(foo)

if __name__ == '__main__':
	popDB()

#-------------------------
# End-of-file
#-------------------------