#!/usr/bin/python
# about: get cutted object as output with wished content-type

import os.path
# cgi
import cgi

# to enable errors to be displayed in the browser:
#import cgitb; cgitb.enable()
# db
#import dbConnect


# allowed content types
allowedContentTypes = ["text/plain", "text/html", "image/jpeg", "image/png", "image/bmp", "image/gif", "audio/x-wav", "audio/mpeg", "application/photoshop", "application/vlc"]
# DEMO MODE: instead of DB an object dict
objectDict = {
"3" : ["0.png"],
"5" : ["2.png", "Von der spekulativen Medientheorie zur Netzkritik.html", "0.png"],
"10": ["0.png"],
"11": ["0.png"],
"18": ["0.png", "Linux_schichten.png", "2.png", "Von der spekulativen Medientheorie zur Netzkritik.html"],
"19": ["0.png", "2.png"],
"25": ["Von der spekulativen Medientheorie zur Netzkritik.html", "Snoop Dogg F Pharrell Drop It Like It's Hot(Dirty).mp3"],
"26": ["0.png", "Linux_schichten.png", "2.png", "Von der spekulativen Medientheorie zur Netzkritik.html", "Snoop Dogg F Pharrell Drop It Like It's Hot(Dirty).mp3"],
"27": ["Linux_schichten.png", "2.png"],
"29": ["naturverhaeltnisse.pdf"],
"37": ["abs-guide.pdf", "elektrosmog.pdf"]
}


# var of post/get parameter
thedata = cgi.FieldStorage()
objectId = thedata.getvalue("objectId", None)
contentType = thedata.getvalue("contentType", "text/html")

if (contentType not in allowedContentTypes and contentType != "hex") or (objectId == None):
	# default content type
	contentType = "text/html"

# basic cgi output header (forwarding to hexdump mustn't have a content-type print out)
if contentType != "hex": 
	print "Content-type: %s\n" % contentType
	#print objectId

if objectId == None:
	print "no objectId given.<br>what do you want to get?"
else:
	
	# cut files together to put out as object...
	# connect
	#dbConnect.connect()
	
	# select
	#sql = "SELECT object, id, path FROM file, cut WHERE cut.file=file.id AND object=%s;"
	#res = dbConnect.executeSelectEscaped(sql, objectId)
	
	# loop through result to cut objects
	outfile = None
	for record in objectDict[objectId]:
		filepath = os.path.join("uploads", record)
		if os.path.isfile(filepath):
			# read file 
			#for line in open(filepath):
			#	print line
			# read the whole file in one shot
			file_contents = open(filepath, 'rb').read()
			# write file...
			if contentType == "hex":
				# hex: write to tmpfile
				outputPath = os.path.join("tmp", "%s.obj" % objectId)
				# open output file to write (only once)
				if not outfile:
					outfile = open(outputPath, "wb")
				# write file
				outfile.write(file_contents)
				
			else:
				# not-hex: write to cgi
				print file_contents
	
	# pass to hexdump.cgi/py...
	if contentType == "hex":
		print "Location: hexdump.cgi?filename=%s\n" % outputPath
	
	# close db connection
	#dbConnect.close()