# Unity Mail, functions for working with configuration file
# Author: Dmitry Shachnev <mitya57@gmail.com>
# License: GNU GPL 3 or higher; http://www.gnu.org/licenses/gpl.html

from gi.repository import GLib
from configparser import RawConfigParser
import subprocess
import webbrowser

config_dir = GLib.get_user_config_dir()

class ConfigFile(RawConfigParser):
	"""Extension of RawConfigParser with some useful additions"""
	
	def __init__(self, filename):
		RawConfigParser.__init__(self, strict=False)
		self.optionxform = str
		self.read(filename)
	
	def get_str_with_default(self, item, defaultvalue = '', section = 'General'):
		if self.has_option(section, item):
			return self.get(section, item)
		else:
			return defaultvalue
	
	def get_bool_with_default(self, item, defaultvalue, section = 'General'):
		if self.has_option(section, item):
			return self.getboolean(section, item)
		else:
			return defaultvalue
	
	def get_int_with_default(self, item, defaultvalue, section = 'General'):
		if self.has_option(section, item):
			return self.getint(section, item)
		else:
			return defaultvalue
	
	def save_with_default(self, item, value, defaultvalue, section = 'General'):
		if value == defaultvalue:
			if self.has_option(section, item):
				self.remove_option(section, item)
		else:
			if not self.has_section(section):
				self.add_section(section)
			self.set(section, item, value)
	
	def save_to_file(self, filename):
		of = open(filename, 'w')
		self.write(of)
		of.close()

default_urls = {
   'Home': 'https://mail.google.com/mail/',
'Compose': 'https://mail.google.com/mail/#compose',
  'Inbox': 'https://mail.google.com/mail/#inbox',
   'Sent': 'https://mail.google.com/mail/#sent' }

def open_url_or_command(name):
	config = ConfigFile(config_dir+'/unity-mail.conf')
	if config.has_option('URLs', name):
		url = config.get('URLs', name)
		if url.startswith('Exec:'):
			subprocess.call(url[5:], shell=True)
		else:
			webbrowser.open(url)
	else:
		try:
			webbrowser.open(default_urls[name])
		except KeyError:
			print('Error: unknown URL name!')
			print_names()

def print_names():
	print('Possible URL names: "Home", "Compose", "Inbox", "Sent"')
