# Copyright (c) 1993 by Sanjay Ghemawat
#############################################################################
# Set of weekdays dialog
#
# Commands
#
#	weekday_set <leader> <resultvar> <initially selected days...>
#
#	Interact with user to determine set of weekdays.
#	The result is a list of elements ranging over 1..7 and is
#	stored in resultvar.  Returns true iff dialog is not cancelled.

# Hidden global variables
#
#	ws_init			Created ws dialog window?
#	ws_done			Is ws interaction finished
#	ws_value(1..7)		Set iff specified weekday was selected

set ws_init 0
set ws_done 0
catch {unset ws_value}
foreach i {1 2 3 4 5 6 7} {
    set ws_value($i) 0
}

proc weekday_set {leader var args} {
    ws_make

    set result [ws_interact $leader $args]
    if $result {
	global ws_value
	upvar $var returnVar

	set returnVar {}
	foreach i {1 2 3 4 5 6 7} {
	    if $ws_value($i) {
		lappend returnVar $i
	    }
	}
    }
    return $result
}

proc ws_make {} {
    global ws_init ws_done
    if {$ws_init} {return}
    set ws_init 1

    set f .ws_dialog

    toplevel $f -class Dialog -geometry ""
    wm title $f Confirm
    wm protocol $f WM_DELETE_WINDOW {set ws_done 0}

    frame $f.top -relief raised -bd 1
    frame $f.mid -relief raised -bd 1
    frame $f.bot -relief raised -bd 1
    frame $f.bot.default -relief sunken -bd 1

    message $f.text -aspect 400 -text "Select set of weekdays on which item should repeat."

    global weekday_name
    foreach i {1 2 3 4 5 6 7} {
	checkbutton $f.w$i\
	    -anchor w\
	    -padx 10m\
	    -relief flat\
	    -variable ws_value($i)\
	    -text $weekday_name($i)
	pack append $f.mid $f.w$i {top fillx}
    }

    button $f.yes -text Okay -command {set ws_done 1}
    button $f.no -text Cancel -command {set ws_done 0}

    pack append $f.top $f.text {right expand fill padx 5m pady 5m}

    pack append $f.bot.default $f.yes {left padx 3m pady 3m}
    pack append $f.bot $f.no {left expand padx 5m pady 5m}
    pack append $f.bot $f.bot.default {left expand}

    pack append $f $f.top {top expand fill}
    pack append $f $f.mid {top fill}
    pack append $f $f.bot {bottom fill}

    bind $f <Control-c> {set ws_done 0}
    bind $f <Return> {set ws_done 1}

    wm withdraw $f
    update
}

proc ws_interact {leader select} {
    global ws_value
    global ws_done
    set f .ws_dialog

    # Set initial selection
    foreach i {1 2 3 4 5 6 7} {
	set ws_value($i) 0
    }
    foreach x $select {
	set ws_value($x) 1
    }

    # Run dialog
    set ws_done -1
    dialog_run $leader $f $f ws_done

    # Construct return value
    return $ws_done
}
