# mesg.tcl
# Implements primitive but effective message catalog


namespace eval ::mesg:: {
    variable messages
    array set messages {}
    variable preferredLang en
    variable availableLanguages 
    array set availableLanguages {English en Spanish es}
}

proc ::mesg::processMesgCatalogDir { dir } {
      variable preferredLang
      ::mesg::processFile [file join $dir messages.en]
      set secondLang [file join $dir messages.$preferredLang]
      if [file exists $secondLang] {
	  ::mesg::processFile $secondLang
      }
}

proc ::mesg::processFile { file } {
    set f [open $file]
    foreach {key text} [read $f] {
        ::mesg::add $key $text
    }
    close $f
}

proc ::mesg::get { key } {
    variable messages
    if ![info exists messages($key)] {
        # If there is no message is that it is yet not translated
	return $key
    } else {
        return $messages($key)
    }
}

proc ::mesg::add { key text } {
    variable messages
    set messages($key) $text
}

proc ::mesg::changeLanguage { lang } {
    if [catch {
	set f [open ../conf/preferredLanguage.conf w]
	puts $f [string tolower $lang]
	close $f
    } dummy] {
	puts "Could not save preferences for language"
    }
}


proc ::mesg::changeLanguageDialog {} {
    catch {destroy .changeLanguage}
    set dialog .changeLanguage
    Dialog $dialog -title "Change preferred Language" \
	    -image localeBig -modal local -anchor c -side bottom
    $dialog add -text Ok
    $dialog add -text Cancel
    set frame [$dialog getframe]
    set origValues [array get ::mesg::availableLanguages]
    set i 0
    set index 0
    set values {}
    foreach {lang code} $origValues {
	if [string match $code $::mesg::preferredLang] {
	    set index $i
	}
	lappend values $lang
	incr i
    }
    set cb [ComboBox $frame.cb -label "Language: " \
	    -values $values]
    $cb setvalue @$index
    pack $cb -fill x -expand true -anchor e
    switch [$dialog draw] {
	0 {
	    ::mesg::changeLanguage \
		    $::mesg::availableLanguages([lindex [$cb cget -values] [$cb getvalue]])
	}
    }
}

# Init preferred language


catch {

    set f [open ../conf/preferredLanguage.conf]
    set ::mesg::preferredLang [string trim [string tolower [read $f]]]
    close $f

} dummy

