from xml.dom import minidom, Node
from functions import isDefined, getConfigDir, createConfigDir
import random
import os.path
from hiscores import *
		
class Options(object):
	instance = None       
	def __new__(theClass): 
		if theClass.instance is None:
			theClass.instance = object.__new__(theClass)
			theClass.instance.file = ""
			theClass.instance.params = []
			theClass.instance.values = []
			theClass.instance.limits = []
			theClass.instance.xmldoc = None
			#theClass.instance.hiscores = None
		return theClass.instance
	
	def __init__(self):
		createConfigDir()
		self.instance.file = ""
		self.instance.params = []
		self.instance.values = []
		self.instance.limits = []
		self.instance.xmldoc = None
		if (os.path.exists(os.path.join(getConfigDir(),"options.xml"))):
			self.load("options.xml")
		else:
			self.loadFromXML("options.xml")
		self.save()
		self.instance.hiscores = HiScores()
		if (os.path.exists(os.path.join(getConfigDir(),"hiscores"))):
			self.instance.hiscores.load()
		else:
			self.instance.hiscores.loadFromXML("hiscores")
		self.instance.hiscores.save()
		
	def __getitem__(self,i):
		if (type(i) == int):
			return self.instance.values[i]
		if (type(i) == str):
			return self.instance.values[self.instance.params.index(i)]
		
	def getParam(self,parname):
		return self.instance.values[self.instance.params.index(parname)]
		
	def load(self, filename):
		self.instance.file = os.path.join(getConfigDir(),filename)
		self.instance.xmldoc = minidom.parse(self.instance.file)
		params = self.instance.xmldoc.getElementsByTagName("param")
		for param in params:
			limit = [0,100]
			if "name" in param.attributes.keys():
				self.instance.params.append(param.attributes["name"].value)
			if "value" in param.attributes.keys():
				self.instance.values.append(float(param.attributes["value"].value))
			if "min" in param.attributes.keys():
				limit[0] = float(param.attributes["min"].value)
			if "max" in param.attributes.keys():
				limit[1] = float(param.attributes["max"].value)
			self.instance.limits.append(limit)

	def loadFromXML(self, filename):
		self.instance.file = os.path.join(getConfigDir(),filename)
		self.instance.xmldoc = minidom.parse(filename)
		params = self.instance.xmldoc.getElementsByTagName("param")
		for param in params:
			limit = [0,100]
			if "name" in param.attributes.keys():
				self.instance.params.append(param.attributes["name"].value)
			if "value" in param.attributes.keys():
				self.instance.values.append(float(param.attributes["value"].value))
			if "min" in param.attributes.keys():
				limit[0] = float(param.attributes["min"].value)
			if "max" in param.attributes.keys():
				limit[1] = float(param.attributes["max"].value)
			self.instance.limits.append(limit)
				
	def save(self):
		file = open(self.instance.file,"w")
		params = self.instance.xmldoc.getElementsByTagName("param")
		for param in params:
			for i in range(len(self.instance.params)):
				if param.attributes["name"].value == self.instance.params[i]:
					param.attributes["value"].value = str(self.instance.values[i])
		file.write(self.instance.xmldoc.toxml())
		file.close()
		
	def saveToXML(self,filename):
		file = open(filename,"w")
		params = self.instance.xmldoc.getElementsByTagName("param")
		for param in params:
			for i in range(len(self.instance.params)):
				if param.attributes["name"].value == self.instance.params[i]:
					param.attributes["value"].value = str(self.instance.values[i])
		file.write(self.instance.xmldoc.toxml())
		file.close()
				
	def setParam(self,parname,val):
		ind = self.instance.params.index(parname)
		if (val > self.instance.limits[ind][1]):
			self.instance.values[ind] = self.instance.limits[ind][1]
		elif (val < self.instance.limits[ind][0]):
			self.instance.values[ind] = self.instance.limits[ind][0]
		else:
			self.instance.values[ind] = val
			
	def write(self):
		for i in range(len(self.instance.params)):
			print "param",self.instance.params[i],"=",self.instance.values[i]
			
#a = Options()
#a.loadFromXML("options2.xml")
#a.write()
#b = Options()
#b.loadFromXML("options2.xml")
#b.write()
#print id(a),id(b)
##print "param",a["BloodAmount"]
#
#class  Singleton (object):
#    instance = None       
#    def __new__(theClassef): 
#        if theClassef.instance is None:
#            theClassef.instance = object.__new__(theClassef)
#            theClassef.instance.x = random.randint(1,32454)
#        return theClassef.instance
#    
#    def write(self):
#        print self.instance.x

#a = Borg()
#b = Borg()
#a.x = 1253
#print a.x,b.x
#a = OptionsContent()
#b = OptionsContent()
#a.loadFromXML("options2.xml")
#a.write()