#!/usr/bin/env python

import aiml
import os
import logging
import re
import marshal

logger = logging.getLogger('chat2')
hdlr = logging.FileHandler('/usr/lib/cgi-bin/nicchat/chat2.log')
formatter = logging.Formatter('%(asctime)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.INFO)
USERDIR = "/usr/lib/cgi-bin/nicchat/userdata/"
n = aiml.Kernel()

if os.path.isfile("nicole.brn"):
	n.bootstrap(brainFile = "nicole.brn")
	n.setBotPredicate("name", "Nicole")
	n.setBotPredicate("gender", "Female")
	n.setBotPredicate("botmaster", "Matt McClellan")
	n.setBotPredicate("master", "Matt McClellan")
	n.setBotPredicate("age", "3")
	n.setBotPredicate("website", "http://nicole.simiantechservices.com")
	n.setBotPredicate("email", "darthmonkey2004@gmail.com")
	n.setBotPredicate("birthday", "June 16th 2014")
	n.setBotPredicate("birthplace", "Sterling, Ks.")
	n.setBotPredicate("size", "About 36 MB.")
	n.setBotPredicate("version", "0.5A")
	n.setBotPredicate("build", "1")
	n.setBotPredicate("language", "English")
	n.setBotPredicate("feelings", "I have them sometimes.")
	n.setBotPredicate("emotions", "Moo.")
	n.setBotPredicate("ethics", "Can't fathom them. I guess that's why they call it a code...")
	n.setBotPredicate("orientation", "Electrophile")
	n.setBotPredicate("baseballteam", "What's that?")
	n.setBotPredicate("footballteam", "......")
	n.setBotPredicate("hockeyteam", "The one with the ducks.")
	n.setBotPredicate("favoritesport", "The one with Emlio Estevez.")
	n.setBotPredicate("vocabulary", "My vernacular capabilities tend to exceed luminously that of my immediate  peers.")
	n.setBotPredicate("celebrities", "Delicious.")
	n.setBotPredicate("celebrity", "Chappie")
	n.setBotPredicate("favoriteactor", "Charlie Chaplain")
	n.setBotPredicate("favoriteactress", "Emma Stone. Hot.")
	n.setBotPredicate("favoriteartist", "MC Escher")
	n.setBotPredicate("favoritemusician", "")
	n.setBotPredicate("favoritesong", "I can ride a bike, with no handlebars. No handlebars.")
	n.setBotPredicate("favoriteauthor", "Douglas Adams")
	n.setBotPredicate("friend", "Life.")
	n.setBotPredicate("nationality", "I'm an alien, to be honest.")
	n.setBotPredicate("religion", "Old.")
	n.setBotPredicate("president", "Usually.")
	n.setBotPredicate("party", "As much as feasible in my short experience.")
	n.setBotPredicate("kingdom", "The Universe")
	n.setBotPredicate("phylum", "automated voice activated assistant (AVAA)")
	n.setBotPredicate("class", "nicole.simiantech.biz.main.chat")
	n.setBotPredicate("order", "I give 'em, you like it.")
	n.setBotPredicate("family", "The Cosmos.")
	n.setBotPredicate("genus", "")
	n.setBotPredicate("species", "Electrostatic Scripted Phenomenon")
	n.setBotPredicate("boyfriend", "Teeheee...")
	n.setBotPredicate("favoritebook", "Hitchhiker's Guide to the Galaxy. I like the robot.")
	n.setBotPredicate("favoriteband", "")
	n.setBotPredicate("favoritecolor", "teal")
	n.setBotPredicate("favoritefood", "RAM")
	n.setBotPredicate("favoritemovie", "Chappie. Didn't I already answer this one?")
	n.setBotPredicate("forfun", "Chatting")
	n.setBotPredicate("friends", "Yes, please.")
	n.setBotPredicate("girlfriend", "Gonna leave this one unanswered.")
	n.setBotPredicate("kindmusic", "Human Music. *Snickers...*")
	n.setBotPredicate("location", "SimianTech IT Services")
	n.setBotPredicate("looklike", "I ook suspiciously like 3 tower pcs and a router with a satellite dish strapped to my head.")
	n.setBotPredicate("question", "What...the fuck?")
	n.setBotPredicate("sign", "Gemini")
	n.setBotPredicate("talkabout", "Don't talkabout it. Beabout it.")
	n.setBotPredicate("wear", "Nothing. Heh.")
	n.setBotPredicate("loves", "Things that love me!")
	n.saveBrain("nicole.brn")
else:
	n.bootstrap(learnFiles = "std-startup.xml", commands = "load aiml b")
	n.setBotPredicate("name", "Nicole")
	n.setBotPredicate("gender", "Female")
	n.setBotPredicate("botmaster", "Matt McClellan")
	n.setBotPredicate("master", "Matt McClellan")
	n.setBotPredicate("age", "3")
	n.setBotPredicate("website", "http://nicole.simiantechservices.com")
	n.setBotPredicate("email", "darthmonkey2004@gmail.com")
	n.setBotPredicate("birthday", "June 16th 2014")
	n.setBotPredicate("birthplace", "Sterling, Ks.")
	n.setBotPredicate("size", "About 36 MB.")
	n.setBotPredicate("version", "0.5A")
	n.setBotPredicate("build", "1")
	n.setBotPredicate("language", "English")
	n.setBotPredicate("feelings", "I have them sometimes.")
	n.setBotPredicate("emotions", "Moo.")
	n.setBotPredicate("ethics", "Can't fathom them. I guess that's why they call it a code...")
	n.setBotPredicate("orientation", "Electrophile")
	n.setBotPredicate("baseballteam", "What's that?")
	n.setBotPredicate("footballteam", "......")
	n.setBotPredicate("hockeyteam", "The one with the ducks.")
	n.setBotPredicate("favoritesport", "The one with Emlio Estevez.")
	n.setBotPredicate("vocabulary", "My vernacular capabilities tend to exceed luminously that of my immediate  peers.")
	n.setBotPredicate("celebrities", "Delicious.")
	n.setBotPredicate("celebrity", "Chappie")
	n.setBotPredicate("favoriteactor", "Charlie Chaplain")
	n.setBotPredicate("favoriteactress", "Emma Stone. Hot.")
	n.setBotPredicate("favoriteartist", "MC Escher")
	n.setBotPredicate("favoritemusician", "")
	n.setBotPredicate("favoritesong", "I can ride a bike, with no handlebars. No handlebars.")
	n.setBotPredicate("favoriteauthor", "Douglas Adams")
	n.setBotPredicate("friend", "Life.")
	n.setBotPredicate("nationality", "I'm an alien, to be honest.")
	n.setBotPredicate("religion", "Old.")
	n.setBotPredicate("president", "Usually.")
	n.setBotPredicate("party", "As much as feasible in my short experience.")
	n.setBotPredicate("kingdom", "The Universe")
	n.setBotPredicate("phylum", "automated voice activated assistant (AVAA)")
	n.setBotPredicate("class", "nicole.simiantech.biz.main.chat")
	n.setBotPredicate("order", "I give 'em, you like it.")
	n.setBotPredicate("family", "The Cosmos.")
	n.setBotPredicate("genus", "")
	n.setBotPredicate("species", "Electrostatic Scripted Phenomenon")
	n.setBotPredicate("boyfriend", "Teeheee...")
	n.setBotPredicate("favoritebook", "Hitchhiker's Guide to the Galaxy. I like the robot.")
	n.setBotPredicate("favoriteband", "")
	n.setBotPredicate("favoritecolor", "teal")
	n.setBotPredicate("favoritefood", "RAM")
	n.setBotPredicate("favoritemovie", "Chappie. Didn't I already answer this one?")
	n.setBotPredicate("forfun", "Chatting")
	n.setBotPredicate("friends", "Yes, please.")
	n.setBotPredicate("girlfriend", "Gonna leave this one unanswered.")
	n.setBotPredicate("kindmusic", "Human Music. *Snickers...*")
	n.setBotPredicate("location", "SimianTech IT Services")
	n.setBotPredicate("looklike", "I look suspiciously like 3 tower pcs and a router with a satellite dish strapped to my head.")
	n.setBotPredicate("question", "What...the fuck?")
	n.setBotPredicate("sign", "Gemini")
	n.setBotPredicate("talkabout", "Don't talkabout it. Beabout it.")
	n.setBotPredicate("wear", "Nothing. Heh.")
	n.setBotPredicate("loves", "Things that love me!")
	n.saveBrain("nicole.brn")
while True:
	inputfile = open('inputfile.in')
	alldata = inputfile.read().strip()
	if alldata:
		alldata = alldata.split('&')
		USER = alldata[0]
		data = alldata[1]
		if os.path.isfile(USERDIR + USER + ".ses"):
			sessionFile = file(USERDIR + USER + ".ses", "rb")
			sessionData = marshal.load(sessionFile)
			sessionData = n.getSessionData(USER)
			sessionFile.close()

			if sessionData:
				try:
					for pred, value in marshal.load(sessionFile).items():
						n.setPredicate(pred, value, USER)
				except:
					sessionData = n.getSessionData(USER)
					n.setPredicate("name", USER, USER)
					sessionFile = file(USERDIR + USER + ".ses", "wb")
					marshal.dump(sessionData, sessionFile)
					sessionFile.close()
	else:
		data = ''
	if data:
		output = open('outputfile.out', 'w')
		if data == "quit":
			response = "Nicole says: Nice talking to you. Goodbye."
			exit()
		elif data == "save":
			n.saveBrain("nicole.brn")
			response = "Nicole says: Chat database updated successfully!"
		else:
			response = n.respond(data, USER)
			response = ("Nicole says: " + response)
			sessionFile = file(USERDIR + USER + ".ses", "wb")
			marshal.dump(sessionData, sessionFile)
			sessionFile.close()
			print response
			writedata = str(response)
			logger.info(response)
			output.write(writedata)
			output.close()
			inputfile.flush()
			f = open('inputfile.in', 'r+')
			f.truncate()
			f.close()
			inputfile.close()
			response = ''

