


class xuiChoice {
    inherit xuiObject

    variable choices
    variable default {}
    private variable selected {}
    
    constructor {} {
    set choices {}
    setXuiClass choice
    }

    method setDefault { choiceName }
    method getDefault {}
    method addChoice { choiceName {text {}} }
    method getChoices {}
    method selectItem { choiceName }
    method selectItems { choiceList }
    method getSelected {}
    method getItemText { choiceName }
    method getText {}
    method clone 
    method copyClone { clone }
    method clear {}
    method reset {}
    method findChoice {choiceName}
}

body xuiChoice::reset {} {
    set selected $default
}

body xuiChoice::clear {} {
     set default {}
     set selected {}
     catch {unset  choices}
     variable choices
     set choices {}
}

body xuiChoice::clone {{parentName {::#auto}}} {
   set clone [xuiChoice $parentName.$name]
   copyClone $clone
   return $clone
}

body xuiChoice::copyClone {clone} {
   xuiObject::copyClone $clone
   $clone clear
   foreach {choiceName text} $choices {
     $clone addChoice $choiceName $text
   }
   $clone setDefault $default
   $clone selectItems $selected
   $clone setXuiClass $xuiClass
}

body xuiChoice::setDefault { choiceName } {
    set result {}
    foreach choice  $choiceName {
	lappend result  [findChoice $choice]
    }
    set default $result
}

body xuiChoice::getDefault { } {
     return $default
}

body xuiChoice::addChoice { choiceName {text {}} } {
    # XXX Sacrifice case sensitivity to ease programming
    # may need to change in the future
    
#    set choiceName [string tolower $choiceName]
    if ![llength $text] {
	set text $choiceName
    } 
    lappend choices $choiceName 
    lappend choices $text
}    

body xuiChoice::getChoices {} {
    return $choices
}

body xuiChoice::selectItem { choiceName } {

    set selected [findChoice $choiceName]
}

body xuiChoice::selectItems { choiceName } {
    set result {}
    foreach choice  $choiceName {
	lappend result  [findChoice $choice]
    }
    set selected $result
}

body xuiChoice::getSelected {} {
    return $selected
}

body xuiChoice::getItemText {choiceName} {
    array set tmp $choices
    return $tmp([findChoice $choiceName])
}


body xuiChoice::getText {} {
    set result {}
    array set tmp $choices
    foreach one $selected {
	append result $tmp($selected)
    }
    return $result
}

body xuiChoice::findChoice {choiceName} {
    set selected [string tolower $choiceName]
    foreach {choice text} $choices {
	if ![string compare [string tolower $choice] $selected] {
	    return $choice
	}
    }
    error "Unknown choice: $choiceName. Known choices: $choices"
}
