import sys,getopt,os,time

class CommandLine:	
	def __init__(self,optionsVariables="",options="",optionsDesc=""):	
		self.optionsVariables = optionsVariables
		self.options = options
		self.optionsDesc = optionsDesc


	def isInt(self,i): 
		try: 
			int(i) 
			return 1 
		except: 
			return 


	def isFloat(self,i): 
		try:
			float(i) 
			return 1 
		except: 
			return 
			
			
	def printOptions(self):
		outString = ""
		print  "----------------------------" + time.strftime('%X') + "----------------------------"
		print "----------------------------------------------------------------\n"
		print "########################OPTIONS#################################\n"
		print "----------------------------------------------------------------\n"
		
		sort = self.options.keys()
		sort.sort()
		for option in sort:
			try:
				outString += "%-30s"%option + "\t" 
				
				
				if option in self.optionsVariables:
					outString += self.optionsVariables[option] + "\t" 
				else:
					outString += "/" + "\t" 
				
				if option in self.optionsDesc:
					outString += "%-60s"%str(self.optionsDesc[option]) + "\t" 
				else:
					outString += "%-60s"%"/" + "\t" 
					
				outString += str(self.options[option]) + "\n"
				
			except:
				pass
		
		print outString


	def usage(self):
		self.printOptions()


	def parseCommandLine(self):
		if len(sys.argv) == 1:
			print '-'*23 + '\nPlease enter arguements\n' + '-'*23
			self.printOptions()
			sys.exit(2)
		else:
			if 	"-h" in sys.argv[1:]:
				self.usage()
				sys.exit(2)
				
			
			try:
				letters = ":".join([x[1] for x in self.optionsVariables.values()] + ["h"])  +":"
				
				opts, args = getopt.getopt(sys.argv[1:],letters, self.optionsVariables.values())
			except getopt.GetoptError,e:
				print e
				sys.exit(2)
			
			output = None
			options = {}
			
			for o, a in opts:
					for option in self.optionsVariables.keys():
						if o == self.optionsVariables[option]:
							if self.isInt(self.options[option]):
								if a.find(".") == -1:
									options[option] = int(a)
								else:
									options[option] = float(a)
							else:
								options[option] = a	
						
							if "inifile" == option:
								if os.path.exists(self.options["inifile"]):
									self.loadIniFile(self.options["inifile"])
								
				
					
			self.options["calling_folder"] = os.path.dirname(sys.argv[0])
			
			return options
			
			
	def loadIniFile(self,iniFile,tag="",notify=False):
		data = open(iniFile).read().strip()
		iniValues = {}
		
		currentTag = ""
		suffixed = False
		
		for line in data.split("\n"):
			if line.count("=") == 1 or line.count("#") == 1:
				try:
					if line[0] == "#":
						tagTmp = line[1:].split("=")[0].strip()
						 
						if line[1:].count("suffixed") > 0:
							suffixed = True
						else:
							suffixed = False
						
						if tagTmp == "type":
							currentTag = line[1:].split("=")[1].strip().split()[0]
							
					else:
						grabOption = False
						
						[option,value] = line.strip().split("=")
						
						if currentTag == "":
							grabOption = True
							
						if currentTag == tag:
							grabOption = True
			
						if grabOption:
							if suffixed:
								bits = option.split("_")
								option = "_".join(bits[:-1])
								type = bits[-1]
								
								if value != "":
									if type == "float":
										iniValues[option] = float(value)
									if type == "int":
										iniValues[option] = int(value)
									if type == "path":
										if os.path.exists(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(iniFile)),value))):
											pass
										else:
											if notify:
												print option + ":" + os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(iniFile)),value)) + " does not exist please. Please fix path in ./settings/utilities.ini"
	
										iniValues[option] = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(iniFile)),value))
										
									if type == "string":
										iniValues[option] = value
									
									
							elif option in iniValues:
								if self.isInt(iniValues[option]):
									if a.find(".") == -1:
										iniValues[option] = int(value)
									else:
										iniValues[option] = float(value)
								else:
									iniValues[option] = value
							else:
								iniValues[option] = value
								
				except Exception,e:
					print e
					raise
					
		return iniValues
		
		
		
		
		
		
		