 #! /usr/bin/python
''' This class generates a javascript file containing a json-like object that simulates a path tree/directory. Salih Israil. 2012'''
import os
import mimetypes
import getopt
import sys
import struct
from shutil import *

class NewTree():
	def __init__(self, myopts):
		#starts the strings that will be generated as the json-like objects
		self.mystring= '//This is the JSON-like object generated by pathgenerator.py\nsiteInfo = { "siteInfo": [\n'
		self.mystring2= '\nversionInfo = {'
		self.fullscreen = 'False'
		self.support = 'None'
		
		
		
		#checks for flags when this class is first called
		try:
			opts, args = getopt.getopt (myopts, "m:" "d:" "f")
			for a, o in opts:
				if a == "-m":
					#getDir initiates the generation of json object and then writes it to a file
					mainf = "Yes"
					self.getDir(str(o), mainf)
				if a == "-d":
					os.chdir(o)
				if a== "-f":
					self.fullscreen = 'True'
					
		except IOError():
				pass	
		self.mystring2 += ' "fullscreen": "'+self.fullscreen+'", '
		self.mystring2 +=  '"support": "'+self.support+'" }'
		#ends the json object in the string after it has been generated in makeTree
		self.mystring +=']\n};\n'
		self.wholestring = self.mystring + self.mystring2
		#write the returned json object into a file
		myfile=open("path.js", "w")
		myfile.write(self.wholestring)
		myfile.close()
	def getDir(self, new, mainf):
		home=os.chdir(new)
		#call function that will actually generate json object
		start=self.makeTree(new, mainf)
		#take the comma off the last element in the array
		self.mystring = self.mystring[:-1] + '\n'
		
		#this function is where the json object is acually generated.
		#the single argument sets the root directory, the top of the tree
	def makeTree(self, home, mainf):
		nhome = "Home"
		if type(home) == list:
				nhome = home[1]
				home = home[0]
		#we cleverly split the directory into a list, whose length we use to create tabs
		#that will give the json object the look and feel of a directory tree
		num = home.split('/')
		over = len(num)
		#we initialize the number of tabs for a particular folder
		#tab = over - 1
		base = '\t'
		star = base # tab
		tab1 = star + base
		tab2 = tab1 + base
		#we create a variable that will be used to close an array in the json object
		tclose1 = tab2 +'],\n'
		#we use index to parse out the name of the current folder represented in the tree
		#which will be used as a name in the name/value relation, which is then hardcoded
		#into the string along with values associated with the folder
		dirname = num[-1]
		self.mystring += tab1+'{"fname":"'+dirname+'", "name":"'+dirname+'", "type":"folder","path": "'+home+'","location":"'+num[-2]+'", "backpath":"'+nhome+'", "show":"'+mainf+'"},'
		#we then list all the elements of the current folder 
		mydir = os.listdir(home)
		#next we iterate through this list to add each entry to the json object
		for entry in mydir:
			#we get the path for the current entry, to be stored as a value in json object
			mypath = home + "/" + entry
			#we get the mime type of current entry, to be stored as value in json object
			mtype=mimetypes.guess_type(entry)
			if os.path.isdir(mypath)== False:
				try:
					#first we make sure it is not a hidden file
					if entry[0]!= '.':
						a = entry.split(".")
						if a.__len__() == 2:
							#in case it is a "m4v" file, we hardcode the type in because mimetypes does not recognize it
							if a[-1] == "m4v": mtype = "m4v"
							#we add the json array to our string
							self.mystring += '\n'+tab1+'{"fname":"'+a[0]+'", "name":"'+entry+'", "type":"'+str(mtype)+'","path":"'+mypath+'","location":"'+num[-1]+'", "backpath":"'+home+'", "show":"None"},'
						else:
							if a.__len__() > 2:
								nname = a[0]
								for part in a[1:-1]:
									nname += "."+part
								#in case it is a "m4v" file, we hardcode the type in because mimetypes does not recognize it
								if a[-1] == "m4v": mtype = "m4v"
								#we add the json array to our string
								self.mystring += '\n'+tab1+'{"fname":"'+nname+'", "name":"'+entry+'", "type":"'+str(mtype)+'","path":"'+mypath+'","location":"'+num[-1]+'", "backpath":"'+home+'", "show":"None"},'

				except IOError:
					pass
		#add a line break after each iteration
		self.mystring += '\n'
		#we recursively go through each directory
		for entry in mydir:
			mypath = home + "/" + entry
			if os.path.isdir(mypath)== True:
				mypath = home + '/' + entry
				if entry[0]!= '.':
					mainf = "No"
					home1=home+'/'+entry
					nhome = [home1, home]
					newBranch=self.makeTree(nhome, mainf)
		return self.mystring

msg= '\n\n\nCopyright 2012. Voila was created by J.Boston, J.Cowell, A.Fermin, S.Israil, and A.Patton with consulting done by M.Wolf. All rights reserved. Unauthorized usage or reproduction of this program will result in serious legal ramifications!!!\n\n\n'
print msg
msgn = "Welcome to the Path Setup."
print msgn 
while True:
		myopts = []
		constant = raw_input('\n\nTo begin enter "y", to exit enter "n": ')
		if constant == 'y':
				constant1 = raw_input('\nEnter complete path for directory of media files you want added to videoserver: ')
				mym = "-m"+constant1
				myopts.append(mym)
				while True:
					constant2 = raw_input('\nNext directory: (If no more, simply presse "ENTER"): ')
					if constant2 == '': break
					else: 
						mym1= "-m" +constant2
						myopts.append(mym1)
				constant5= raw_input('\nDestination of the path file: ')
				myc="-d" +constant5
				myopts.append(myc)
				NewTree(myopts)
				
				msg1='Your video server is now set up. Enjoy yourself!\n\n\n'
				print msg1
				break
