"""
Theme manager for WeeChat. 
It loads configuration parameters from file 
and allows to create new theme out of current configuration.

by Stalwart <stlwrt@gmail.com>

Licensed under GNU GPL v2

"""

## ---------- Code starts here ----------
import weechat
import os

VERSION = "0.2.3"

weechat.register("theme", VERSION, "", "Theme manager for WeeChat")

THEMEDIR = weechat.get_info("weechat_dir") + '/themes'

weechat.add_command_handler("theme", "parameter_parser", "Apply and create themes", "[load <name> | save <name>]", "", "load|save")

settings = [
		'look_startup_logo',
		'look_startup_version',
		'look_weechat_slogan',
		'look_buffer_timestamp',
		'look_color_nicks_number',
		'look_color_actions',
		'look_nicklist',
		'look_nicklist_position',
		'look_nicklist_min_size',
		'look_nicklist_max_size',
		'look_no_nickname',
		'look_nickmode',
		'look_nickmode_empty',
		'look_nick_prefix',
		'look_nick_suffix',
		'look_align_nick',
		'look_align_other',
		'look_align_size',
		'look_align_size_max',
		'look_infobar',
		'look_infobar_timestamp',
		'look_infobar_seconds',
		'look_infobar_delay_highlight',
		'look_hotlist_names_count',
		'look_hotlist_names_level',
		'look_hotlist_names_length',
		'look_read_marker',
		'look_input_format',
		'col_separator',
		'col_title',
		'col_title_bg',
		'col_chat',
		'col_chat_time',
		'col_chat_time_sep',
		'col_chat_prefix1',
		'col_chat_prefix2',
		'col_chat_server',
		'col_chat_join',
		'col_chat_part',
		'col_chat_nick',
		'col_chat_host',
		'col_chat_channel',
		'col_chat_dark',
		'col_chat_highlight',
		'col_chat_bg',
		'col_chat_read_marker',
		'col_chat_read_marker_bg',
		'col_status',
		'col_status_delimiters',
		'col_status_channel',
		'col_status_data_msg',
		'col_status_private',
		'col_status_highlight',
		'col_status_data_other',
		'col_status_more',
		'col_status_bg',
		'col_infobar',
		'col_infobar_delimiters',
		'col_infobar_highlight',
		'col_infobar_bg',
		'col_input',
		'col_input_server',
		'col_input_channel',
		'col_input_nick',
		'col_input_delimiters',
		'col_input_bg',
		'col_nick',
		'col_nick_away',
		'col_nick_chanowner',
		'col_nick_chanadmin',
		'col_nick_op',
		'col_nick_halfop',
		'col_nick_voice',
		'col_nick_more',
		'col_nick_sep',
		'col_nick_self',
		'col_nick_color1',
		'col_nick_color2',
		'col_nick_color3',
		'col_nick_color4',
		'col_nick_color5',
		'col_nick_color6',
		'col_nick_color7',
		'col_nick_color8',
		'col_nick_color9',
		'col_nick_color10',
		'col_nick_private',
		'col_nick_bg',
		'col_chat_dcc_selected',
		'col_dcc_waiting',
		'col_dcc_connecting',
		'col_dcc_active',
		'col_dcc_done',
		'col_dcc_failed',
		'col_dcc_aborted'
]

def themes_dir_available(writeable):
	if not os.access(THEMEDIR, os.F_OK):
		os.mkdir(THEMEDIR, 0700)
	if writeable:
		if os.access(THEMEDIR, os.W_OK):
			return 1
		else:
			return 0
	else:
		if os.access(THEMEDIR, os.R_OK):
			return 1
		else:
			return 0

def save_theme(theme_filename):
	if themes_dir_available(1):
		try:
			themefile = open("%s/%s" % (THEMEDIR, theme_filename), 'wU')
		except:
			weechat.print_infobar(3, "Bad theme name, try another")
		else:
			themefile.write("# This WeeChat theme has been generated by Themes v.%s\n" % VERSION)
			for variable in settings:
				try:
					value = weechat.get_config(variable)
				except:
					weechat.prnt("Unable to get the value of %s" % variable)
				else:
					themefile.write("%s=%s\n" % (variable, value))
					themefile.flush()
			themefile.close()
			weechat.print_infobar(3, "Theme %s saved" % theme_filename)

def load_theme(theme_filename):
	if themes_dir_available(0):
		if os.access("%s/%s" % (THEMEDIR, theme_filename), os.F_OK):
			themefile = open("%s/%s" % (THEMEDIR, theme_filename), 'rU')
			lines = themefile.readlines()
			for line in lines:
				if ((len(line) > 3) and (line[0] != '#') and (line.find("="))):
					try:
						weechat.set_config(line[:line.find("=")], line[line.find("=")+1:].replace("\n", ""))
					except:
						weechat.prnt("Unable to set the value of %s" % variable)
			weechat.print_infobar(3, "Theme %s applied" % theme_filename)
		else:
			weechat.print_infobar(3, "Theme %s doesn't exist" % theme_filename)
			themefile.close()

def list_themes():
	if themes_dir_available(0):
		files = os.listdir(THEMEDIR)
		if len(files):
			weechat.prnt('Available themes:')
			for filename in files:
				if filename[-9:] == '.weetheme':
					weechat.prnt("    %s" % filename[:-9])
		else:
			weechat.prnt('Theme directory is empty, you can create new theme out of your current configuration by executing "/theme save <name>". Additional themes available on http://weechat.flashtux.org')
	else:
		weechat.prnt('Theme directory is not available. Please, check access rights')

def parameter_parser(server, args):
	if ((args != '') & (len(args.split()) == 2)):
		if args.split()[0] == 'save':
			save_theme(args.split()[1] + '.weetheme')
		elif args.split()[0] == 'load':
			load_theme(args.split()[1] + '.weetheme')
		else:
			weechat.prnt('Invalid parameter, must be "load" or "save"')
	else:
		list_themes()
	return weechat.PLUGIN_RC_OK


