# Tabimages plugin for Tkabber
# Written by Renji
# jabber id: rejjin@jabber.dk
# e-mail: webrenji@gmail.com

namespace eval themes {
	
	variable script_dir [file dirname [info script]]
	
	::msgcat::mcload [file join $script_dir msgs]
	
	custom::defgroup Plugins [::msgcat::mc "Plugins options."] \
	-group Tkabber	
	
    custom::defgroup Themes [::msgcat::mc "Color theme options"] \
	-group Plugins	
	
	hook::add finload_hook [namespace code handle] 
		
}

proc themes::handle { } {
variable tkabber_theme

	set themes [get_themes_from_dir]
	custom::defvar tkabber_theme Default \
		[::msgcat::mc "Tkabber color theme (Need restart)."] -type options \
		-values $themes -group Themes
		
	add_trace_to_tkabber_theme
}

proc themes::add_trace_to_tkabber_theme { } {
variable tkabber_theme
	trace add variable [namespace current]::tkabber_theme write \
		[namespace current]::change_theme
}
		
proc themes::change_theme { who work value } {
variable tkabber_theme
	save_theme $tkabber_theme
}
		
proc themes::save_theme { theme } {

	set cache [open [file join $::configdir tkabber-theme] w]
	puts $cache $theme
	close $cache
}

proc themes::load_theme { } {
	
	set path [file join $::configdir tkabber-theme]
	
	if { [file exist $path] == 0 } {
		return Default
	}
	
	set cache [open $path r]
	gets $cache theme
	close $cache
	
	return $theme
}

proc themes::get_themes_from_dir { } {
variable script_dir

	set themes { Default Default } 
	set path [file join $script_dir xrdb]
	
	foreach theme [glob -nocomplain -directory $path *.xrdb] {
		lappend themes [file normalize $theme] \
			[file tail [file rootname $theme]]
	}
	
	return $themes
}

#########################################################
proc themes::init_theme { } {
	set theme [load_theme]
		
	if { $theme ne "Default" } {
		if { [catch { option readfile $theme } out] } {
			tk_messageBox -icon warning \
			-message [::msgcat::mc "Theme\
			%s with error!\n%s" $theme $out]
			save_theme Default
		}
	}
}

[namespace current]::themes::init_theme
#########################################################


