#!/usr/bin/python
# -*- coding: utf-8 -*-

import os.path
import ConfigParser

class Config():
	"""Classe contenant la configuration"""
	def __init__(self, main_window):
		self.read_file()
		self.infos["Data"]["main_window"] = main_window
	
	def read_file(self):
		"""Récupère la configuration du fichier FramaKioskTune.ini"""
		self.infos = {}
		if os.path.isfile("FramaKioskTune.ini"):
			self.config = ConfigParser.ConfigParser()
			self.config.read('FramaKioskTune.ini')
		else:
			self.writeDefault()
		
		self.infos['FramaKioskTune'] = {}
		self.infos['FramaKioskTune']['FramaVer'] = self.readStr('FramaKioskTune', 'FramaVer', '2.1')
		self.infos['FramaKioskTune']['FramaRoot'] = self.readStr('FramaKioskTune', 'FramaRoot', '../../..')
		self.infos['FramaKioskTune']['FramaKioskPath'] = self.readStr('FramaKioskTune', 'FramaKioskPath', '../../FramaKioskPortable')
		
		self.infos['Data'] = {}
		self.infos['Data']['Version'] = "0.5.1"
	
	def writeDefault(self):
		"""Crée le fichier FramaKioskTune.ini avec la configuration par défaut"""
		self.write({'FramaKioskTune': {'FramaRoot': '../../..', 'FramaKioskPath': '../../FramaKioskPortable'}})
		
	def write(self, infos = None):
		"""Crée le fichier FramaKioskTune.ini"""
		if infos == None:
			infos = self.infos
			
		self.config = ConfigParser.RawConfigParser()
		
		for section in infos.keys():
			if section != "Data":
				if not self.config.has_section(section):
					self.config.add_section(section)
				for element in infos[section].keys():
					self.config.set(section, element, infos[section][element])
		
		self.config.write(open('FramaKioskTune.ini', 'wb'))
	
	def readStr(self, section, element, default = ""):
		"""Récupère une chaîne"""
		try:
			return self.config.get(section, element)
		except:
			return default
	
	def readBool(self, section, element, default = True):
		"""Récupère un booléen"""
		try:
			bool = self.config.get(section, element)
			return self.strToBool(bool, default)
		except:
			return default
	
	def strToBool(self, str, default = True):
		"""Convertie une chaîne en booléen"""
		if str == False or str == "False" or str == "false" or str == "0" or str == 0:
			return False
		elif str == True or str == "True" or str == "true" or str == "1" or str == 1:
			return True
		else:
			return default
		
	def get(self, section = None, element = None):
		"""Renvoie l'information passée en paramètres.
		   Si element = None, renvoie la section.
		   Si section = None, renvoie la configuration."""
		if section is None:
			return self.infos
		else:
			if element is None:
				return self.infos[section]
			else:
				return self.infos[section][element]
	
	def set(self, section, element, value):
		"""Modifie la valeur d'une information"""
		self.infos[section][element] = value
		self.write()
