def main():
	form = cgi.FieldStorage()
	
	#userprof_form = form.getvalue('user') #email of userprofile
	#email = form.getvalue('email') #email of current user
	name = form.getvalue('name')
	born = form.getvalue('country')
	birthdate = form.getvalue('birth_date')
	gender = form.getvalue('gender') 	
	description = form.getvalue('desc')
	illustratorbooks = form.getlist('illustratorbooks')

	#TODO: If current user != email 

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
                cur.execute(command)
                user= cur.fetchone()

		command = "SELECT * from Illustrators WHERE lower(IllustratorName)=lower('" + name + "')"
		cur.execute(command)
		writer_ = cur.fetchone()		
		

		sidebar = utilities.getSideBar(email,user[9], cur)
		
		if writer_  is not None :
			createform = []
			createform.append(name)
			createform.append(birthdate)
			createform.append(gender)
			createform.append(description)

			error = '<strong>Database Error:</strong> Illustrator with name ' + name + ' already exists.' 
                        countryDropDown = utilities.generateCountryDropDown(born)
			bookitems = utilities.getBookItems(illustratorbooks, cur)	
			print display("illustrator-profile-create.html").render(user=user,createform=createform,sidebar=sidebar,countryDropDown=countryDropDown,error=error,bookitems=bookitems)
		else :
			# Required Fields
			insert_command_1 = "INSERT INTO Illustrators(IllustratorName "
			insert_command_2 = "VALUES ( '" + name + "'"

			# Born / Country
			if born is not None:
				insert_command_1 = insert_command_1 + ", Born "
				insert_command_2 = insert_command_2 + " ,'" + born + "' "

			# Birthdate
			if birthdate is not None:
				insert_command_1 = insert_command_1 + ", Birthdate "
				insert_command_2 = insert_command_2 + " ,'" + birthdate + "' "

			# Gender
			if gender is not None :
				insert_command_1 = insert_command_1 + ", Gender "
				insert_command_2 = insert_command_2 + " ,'" + gender + "' "

			# Description
			if description is not None:
				insert_command_1 = insert_command_1 + ", IllustratorDescription "
                                insert_command_2 = insert_command_2 + " ,'" + description + "' "
		
			 # upload image is user specified
                	if form.has_key('image_file'):

                        	fileitem = form['image_file']
                        	if fileitem.file :
                                	extension = os.path.splitext(fileitem.filename)[1]
                                	if extension != '' :
                                        	fout = file ("model/writers/illustrator-" +  name + extension , 'wb')
                                        	while 1:
                                                	chunk = fileitem.file.read(100000)
                                                	if not chunk: break
                                                	fout.write(chunk)
                                        	fout.close()
                                        	insert_command_1 = insert_command_1 + ", IllustratorImage " 
						insert_command_2 = insert_command_2 + ", 'model/writers/illustrator-" +  name + extension  + "' "


			insert_command_1 = insert_command_1 + ") "
			insert_command_2 = insert_command_2 + ") " 
			cur.execute(insert_command_1 + insert_command_2)

			# Associate Books to Writer
                        for book in illustratorbooks:
                                command = "INSERT INTO BookIllustrator(ISBN, IllustratorName) VALUES (" + book + ",'"  + name + "')"
                                cur.execute(command)
                	con.commit()

			command = "SELECT * FROM Users WHERE Email = '" + email + "'";
			cur.execute(command)
			user_= cur.fetchone() #

			command = "SELECT * from Illustrators WHERE IllustratorName ='" + name + "'"
			cur.execute(command)
			illustrator_ = cur.fetchone()

			command = "SELECT ISBN, Title, Price, Image from ComicBooks NATURAL JOIN BookIllustrator NATURAL JOIN Illustrators WHERE IllustratorName='" + name + "'"
		
			cur.execute(command)
			rows = cur.fetchall()
			titles = []
			for row in rows:
				titles.append(row)

			command = "SELECT Genre from ComicBooks NATURAL JOIN BookGenre NATURAL JOIN BookIllustrator WHERE IllustratorName ='" + name + "'"
			cur.execute(command)
			genres = cur.fetchall()
			genres_ = []
			for genre in genres:
				if genre not in genres_:
					genres_.append(genre)

                	sidebar = utilities.getSideBar(email,user[9], cur)
			successmsg = '<strong>Success:</strong> Illustrator has been created.'
			print display("illustrator-profile.html").render(sidebar=sidebar,user=user_,illustrator=illustrator_,titles=titles,genres=genres_,success=successmsg)		
                	sess.close()
	except mdb.Error, e:
	    if con:
	        con.rollback()
def main():
	form = cgi.FieldStorage()
	
	illustrator= form.getvalue('illustrator') 
	#email = form.getvalue('email') #email of current user
	action = form.getvalue('action') # action 

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		if email is None:
			print "Location: login.py?redirect=1\r\n"
		
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user_= cur.fetchone() #

		if action != 'create' :
			command = "SELECT * from Illustrators WHERE IllustratorName ='" + illustrator + "'"
			cur.execute(command)
			illustrator_ = cur.fetchone()

			command = "SELECT ISBN, Title, Price, Image from ComicBooks NATURAL JOIN BookIllustrator NATURAL JOIN Illustrators WHERE IllustratorName='" + illustrator + "'"
		
			cur.execute(command)
			rows = cur.fetchall()
			titles = []
			for row in rows:
				titles.append(row)

			command = "SELECT Genre from ComicBooks NATURAL JOIN BookGenre NATURAL JOIN BookIllustrator WHERE IllustratorName ='" + illustrator + "'"
			cur.execute(command)
			genres = cur.fetchall()
			genres_ = []
			for genre in genres:
				if genre not in genres_:
					genres_.append(genre)

		sidebar = utilities.getSideBar(email,user_[9], cur)

		if action == 'create' :
			countryDropDown = utilities.generateCountryDropDown(None)
			bookitems = utilities.getBookItems([], cur)
			print display("illustrator-profile-create.html").render(user=user_,createform=None,sidebar=sidebar,bookitems=bookitems,countryDropDown=countryDropDown)
		elif action == 'edit':
			countryDropDown = utilities.generateCountryDropDown(illustrator_[3])

			selectedBooks = []
			for title in titles :
				selectedBooks.append(title[0])
			bookitems = utilities.getBookItems(selectedBooks, cur)
			print display("illustrator-profile-edit.html").render(sidebar=sidebar,user=user_,illustrator=illustrator_,bookitems=bookitems,countryDropDown=countryDropDown)
		else :
			print display("illustrator-profile.html").render(sidebar=sidebar,user=user_,illustrator=illustrator_,titles=titles,genres=genres_)
		sess.close()

	except mdb.Error, e:
	    if con:
	        con.rollback()
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email')
	genre = form.getvalue('genre')
	action = form.getvalue('action')
	genredesc = form.getvalue('genredesc')
	genrecreate = form.getvalue('genrecreate')
	genrebooks = form.getlist('genrebooks')

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
                cur.execute(command)
                user= cur.fetchone()

		if action == None :
			if genre != None :
				command = "SELECT * FROM Genres where Genre='" + genre + "'";
				cur.execute(command)
				genreform= cur.fetchone()

				# Get books associated with genre
				command = "SELECT ISBN from ComicBooks NATURAL JOIN BookGenre WHERE Genre='" + genre + "' order by Title"
				cur.execute(command)
				rows = cur.fetchall()		

				titles = []
				for row in rows:
					titles.append(row[0])

				bookitems = utilities.getBookItems(titles, cur)
			else :
				genreform = None
        			bookitems = utilities.getBookItems([], cur)	

			sidebar = utilities.getSideBar(email, user[9], cur)

			print display("genre-create-update.html").render(user=user,sidebar=sidebar,genre=genre,genreform=genreform,bookitems=bookitems)
			return

		else :
			# Update
			if genre != None :
				update_command = "UPDATE Genres SET "
				
				if genredesc == None:
					update_command = update_command + " GenreDesc = NULL "
				else :
					update_command = update_command + " GenreDesc = '" + genredesc + "' "
				
				update_command =  update_command + " WHERE Genre = '" + genre +  "'"
				cur.execute(update_command)
				

				command = "DELETE FROM BookGenre WHERE Genre = '"  + genre + "'"
				cur.execute(command)

				# Associate Books to Genre
                                for book in genrebooks:
                                	command = "INSERT INTO BookGenre(ISBN, Genre) VALUES (" + book + ",'"  + genre + "')"
                                        cur.execute(command)
                                con.commit()


                        	command = "SELECT * from ComicBooks NATURAL JOIN BookGenre WHERE Genre='" + genre + "'"
                        	cur.execute(command)
                        	rows = cur.fetchall()
                        	titles = []
                        	for row in rows:
                                	titles.append(row)

                        	sidebar = utilities.getSideBar(email, user[9], cur)
				success = '<strong>Success: </strong> Genre has been updated.'
                        	print display("home.html").render(user=user,titles=titles,sidebar=sidebar,genre=genre,genredesc=genredesc,search=' ',success=success)
			else :
				# Check if genre exists
				command = "SELECT Genre from Genres where Genre = '" + genrecreate + "'"
				cur.execute(command)
				genreRecord = cur.fetchone()

				if genreRecord is not None:
					genreform = []
					genreform.append(genrecreate)
					genreform.append(genredesc)
					sidebar = utilities.getSideBar(email, user[9], cur)
					bookitems = utilities.getBookItems(genrebooks, cur)
					error = "<strong>Database Error:</strong>  Genre " + genrecreate + " already exists! Provide another genre name."
					sidebar = utilities.getSideBar(email, user[9], cur)
					print display("genre-create-update.html").render(user=user,sidebar=sidebar,genre=genre,genreform=genreform,bookitems=bookitems,error=error)
				else :
					insert_command = "INSERT INTO Genres(Genre, GenreDesc) VALUES ('" + genrecreate + "','" + genredesc + "') "
					cur.execute(insert_command)

					# Associate Books to Genre
					for book in genrebooks:
						command = "INSERT INTO BookGenre(ISBN, Genre) VALUES (" + book + ",'"  + genrecreate + "')"
						cur.execute(command)
					con.commit()

					genre = genrecreate 			 
					command = "SELECT * from ComicBooks NATURAL JOIN BookGenre WHERE Genre='" + genre + "'"
                                	cur.execute(command)
                                	rows = cur.fetchall()
                                	titles = []
                                	for row in rows:
                                        	titles.append(row)

                                	sidebar = utilities.getSideBar(email, user[9], cur)
					success = '<strong>Success: </strong> Genre '  + genrecreate + ' has been created.'
                                	print display("home.html").render(user=user,titles=titles,sidebar=sidebar,genre=genre,genredesc=genredesc,search=' ',success=success)			

	except mdb.Error, e:
	    if con:
	        con.rollback()