proc tksendpr_usage {{str ""}} {
    bell
    wm withdraw .
    tk_dialog .tkgnatsError "TkGnats Error" \
            "${str}usage: tksendpr -server 'ServerInfo' \[-categories 'list'\] \
             \[-classes 'list'\] \[-states 'list'\] \
            \[-db 'database'\] \[-submitters 'list'\] \[-responsible 'list'\]" "error" 0 "OK"
    exit
}

proc tksendpr_process_args {} {
    global TkGnats argc argv env

    set TkGnats(CurrentProgram) tksendpr
    
    if {$argc != 0} {
	if {$argc%2 != 0} {
	    tksendpr_usage
	}
    }
    set addressval ""
    for {set x 0} {$x<$argc} {incr x 2} {
	set opt [lindex $argv $x]
	set val [lindex $argv [expr $x+1]]
	switch -exact -- $opt -server {
            set TkGnats(ServerInfo) $val
        } -categories {
	    set TkGnats(CategoryList)  $val
	} -submitters {
	    set TkGnats(SubmitterList) $val
        } -responsible {
            set TkGnats(ResponsibleFile) $val
        } -classes {
            set TkGnats(ClassesFile) $val
        } -states {
            set TkGnats(StatesFile)  $val
	} default {
	    tksendpr_usage "Illegal option pair:\n'$opt $val'\n\n"
	}
    }

    if {![info exists TkGnats(ServerInfo)]} {
        tksendpr_usage "No -server argument given.\n\n"
    }
    
    foreach var {TKGNATSLIB TKGNATSINI} {
        if {[info exists env($var)]} {
            set TkGnats($var) $env($var)
        }
    }
    
    set TkGnats(lib) $TkGnats(TKGNATSLIB)

    if {[info exists TkGnats(TKGNATSINI)]} {
        if {[file readable $TkGnats(TKGNATSINI)]} {
            source $TkGnats(TKGNATSINI)
        } {
            bell
            wm withdraw .
            tk_dialog .tkgnatsError "TkGnats Error" \
                    "TkGnats INI file '$TkGnats(TKGNATSINI)' not readable" "error" 0 "OK"
            exit
        }
    }

    if {[file exists $TkGnats(lib)/tkgnatsini]} {
        source       $TkGnats(lib)/tkgnatsini
    }
}

tksendpr_process_args

foreach f { tkpr_library.tcl tkprhelp.tcl tkprfont.tcl tkprdatesel.tcl } {
    source $TkGnats(lib)/$f
}

if {[get_gnats_config] == "-1"} {
    exit
}

#TTD remove me after testing
#set TkGnats(ReleaseBased) 1

proc headingMsg {a} {
    .action.msg configure -text $a
    update idletasks
}

# Assemble the problem report in gnats format from the fields in
# Before assembly some of the widgets are checked for validity.

proc send_report {} {
    global TkGnats Tksendpr frm
    
    flush_singletext $Tksendpr(singletextflds)
    flush_multitext
    
    # check all the fields first...

    foreach v {
	Confidential Severity Priority Class Category Submitter
    } {
	global $v
	switch -exact -- [set $v] "" {
	    Msg "An option from '$v' must be selected."
	    return -1
	}
    }

    if {[lsearch -exact $TkGnats(CategoryList) $Category] < 0} {
        Msg "You have specified an invalid Category!"
        return -1
    }
        
    if {[lsearch -exact $TkGnats(SubmitterList) $Submitter] < 0} {
        Msg "You have specified an invalid Submitter-Id!"
        return -1
    }
     
    foreach t {
	Originator Synopsis Reply-To Description How-To-Repeat 
    } {
	if {$t == "Description" || $t == "How-To-Repeat"} {
            set x $frm(>$t)
        } {
            set x [textget $t]
        }
	set x [string trim $x " \n\t\f!:~-#_?"]
	# If a change request, don't demand a How-To-Repeat
	if {$t == "How-To-Repeat"} {
	    global Class
	    if {$Class == "change-request"} {
		continue
	    }
	}
	switch -exact --  $x "" {
	    Msg "Field '$t' is not complete.\n" "Type in something descriptive."
	    return -1
	}
    }

    set flist {
	Originator Release Synopsis Reply-To
    }

    if {$TkGnats(ReleaseBased)} {
	lappend flist Keywords $TkGnats(Quarter) Date-Required
    }
    
    foreach t $flist {
	if {[string first "|" [textget $t]] != -1} {
	    Msg " '|' is an illegal character for the '$t' field!"
	    return -1
	}
    }

    # ok, now send off the report

    set mailtxt ""
    append mailtxt "From: $TkGnats(EmailAddr)\n"
    append mailtxt "Reply-To: [string trim [textget Reply-To]]\n"
    append mailtxt "To: $TkGnats(GNATS_ADDR)\n"
    append mailtxt "Subject: [string trim [textget Synopsis]]\n"
    append mailtxt "X-send-pr-version: $Tksendpr(version)\n"
    append mailtxt "\n"
    #### End of std mail headers

    append mailtxt ">Submitter-Id: $Submitter\n"
    foreach v {
	Confidential Severity Priority Category Class
    } {
	append mailtxt ">${v}:	[set $v]\n"
    }

    set flist {
	Synopsis Originator Release 
    }
    
    if {$TkGnats(ReleaseBased)} {
	lappend flist Keywords $TkGnats(Quarter) Date-Required
    }
    
    foreach t $flist {
	append mailtxt ">${t}: [textget $t]\n"
    }

    foreach t {
	Environment Description How-To-Repeat Fix Organization
    } {
	append mailtxt ">${t}:\n$frm(>$t)\n"
    }

    #
    # mail the assembled problem report file to the gnats system
    #

    headingMsg "Sending Report to $TkGnats(GNATS_ADDR)..."
    if {[TkGnats_sendmail $TkGnats(GNATS_ADDR) $mailtxt] == "-1"} {
        headingMsg "Sending Report to $TkGnats(GNATS_ADDR)...***ERROR***"
        return -1
    } {
        headingMsg "Sending Report to $TkGnats(GNATS_ADDR)...Done"
    }

    #
    # clear out some fields
    #

    set flist {
	Synopsis
    }

    if {$TkGnats(ReleaseBased)} {
	lappend flist Keywords $TkGnats(Quarter) Date-Required
    }

    foreach t $flist {
	textset $t ""
    }
    
    foreach t {
	Environment Description How-To-Repeat Fix Organization
    } {
	set frm(>$t) ""
    }
    .multiline.text delete 1.0 end
    switch_txt ">Description" $Tksendpr(multitextflds)
    # Some folks may not want these reset
    set frm(>Environment)  [env_fld_text]
    set frm(>Organization) [org_fld_text]
    return 0
}

proc send_report_and_exit {} {
    if {[send_report] == 0} {
	Exit 0
    }
}

# bail out completely
proc cancel_report {} {
    Exit 0
}

proc snd_category_listbox {p category_list} {
    global TkGnats Tksendpr Category Category_wid
    set Category ""

    frame  $p.cat -relief groove  -borderwidth 2
    pack   $p.cat -side top -expand true -fill both
    button $p.cat.msg -anchor w -text "Category: " -width 14 -command "helpMsg Category" \
            -relief flat -padx 0 -pady 0 -borderwidth 0
    set Category_wid [expr 2 + [get_max_strlen $category_list]]
    set ew [entry  $p.cat.ent -width $Category_wid -insertwidth 1 -insertofftime 400 \
            -relief sunken -borderwidth 2 -background $TkGnats(EditFieldBackground) -highlightthickness 2 \
            -textvariable Category]
    lappend Tksendpr(tlist) $ew
    trace variable Category w set_snd_category_ew
    set_focus_style $ew
    bind $ew <BackSpace> { tkEntrySetCursor %W [%W index insert] }
    bind $ew <Control-h> { tkEntrySetCursor %W [%W index insert] }
    set height [llength $category_list]
    if {$height > 6 } {
        set height 6
    }
    scrollbar $p.cat.sb -command "$p.cat.list yview" -borderwidth 2 -relief sunken
    listbox $p.cat.list -yscroll "$p.cat.sb set" -setgrid 1 -relief sunken -borderwidth 2 \
            -width $Category_wid -height $height -exportselection false
    eval   $p.cat.list insert end $category_list
    pack   $p.cat.msg  -side left  -anchor n
    pack   $p.cat.ent  -side left  -anchor n
    pack   $p.cat.sb   -side left  -fill y
    pack   $p.cat.list -side right -fill both -expand true
    bind   $p.cat.list <B1-ButtonRelease> "set_snd_category $p.cat.ent %W %y"
    return $p.cat.list
}

proc snd_submitter_listbox {p submitters_list} {
    global TkGnats Tksendpr Submitter Category_wid
    set Submitter ""

    frame  $p.sub -relief groove  -borderwidth 2
    pack   $p.sub -side top -expand true -fill both
    button $p.sub.msg -anchor w -text "Submitter-Id: " -width 14 -command "helpMsg Submitter-Id" \
            -relief flat -padx 0 -pady 0 -borderwidth 0
    set wid [expr 2 + [get_max_strlen $submitters_list]]
    if {$Category_wid > $wid} {
        set wid $Category_wid
    }
    set ew [entry  $p.sub.ent -width $wid -insertwidth 1 -insertofftime 400 \
            -relief sunken -borderwidth 2 -background $TkGnats(EditFieldBackground) -highlightthickness 2 \
            -textvariable Submitter]
    lappend Tksendpr(tlist) $ew
    trace variable Submitter w set_snd_submitter_ew
    set_focus_style $ew
    bind $ew <BackSpace> { tkEntrySetCursor %W [%W index insert] }
    bind $ew <Control-h> { tkEntrySetCursor %W [%W index insert] }
    set height [llength $submitters_list]
    if {$height > 6 } {
        set height 6
    }
    scrollbar $p.sub.sb -command "$p.sub.list yview" -borderwidth 2 -relief sunken
    listbox $p.sub.list -yscroll "$p.sub.sb set" -setgrid 1 -relief sunken -borderwidth 2 \
            -width $wid -height $height -exportselection false
    eval   $p.sub.list insert end $submitters_list
    pack   $p.sub.msg  -side left  -anchor n
    pack   $p.sub.ent  -side left  -anchor n
    pack   $p.sub.sb   -side left  -fill y
    pack   $p.sub.list -side right -fill both -expand true
    bind   $p.sub.list <B1-ButtonRelease> "set_snd_submitter $p.sub.ent %W %y"
    return $p.sub.list
}

proc set_snd_category_ew {a b c} {
    upvar #0 $a f
    global TkGnats
    quickfill_entry_from_listbox f .eboxs.clb.cat.ent .eboxs.clb.cat.list $TkGnats(CategoryList)
}
 
proc set_snd_submitter_ew {a b c} {
    upvar #0 $a f
    global TkGnats
    quickfill_entry_from_listbox f .eboxs.slb.sub.ent .eboxs.slb.sub.list $TkGnats(SubmitterList)
}

proc set_snd_category {ent w y} {
    global Category
    trace vdelete Category w set_snd_category_ew
    $ent delete 0 end
    set idx [$w nearest $y]
    set Category [$w get $idx]
    trace variable Category w set_snd_category_ew
}

proc set_snd_submitter {ent w y} {
    global Submitter
    trace vdelete Submitter w set_snd_submitter_ew
    $ent delete 0 end
    set idx [$w nearest $y]
    set Submitter [$w get $idx]
    trace variable Submitter w set_snd_submitter_ew
}

proc env_fld_text {} {
    global TkGnats tcl_platform
    set txt ""

    if {[info exists TkGnats(ENVIRONMENT)]} {
        set txt $TkGnats(ENVIRONMENT)
    } {
        if {[catch {exec uname -a} result]} {
            set result "$tcl_platform(os) [info hostname] $tcl_platform(osVersion) $tcl_platform(machine)"
        }
        append txt "System: $result\n"
        
        if {![catch {exec arch} result]} {
            append txt "Architecture: $result\n"
        }
        
        if {![catch {exec xdpyinfo | fgrep endor} result]} {
            append txt "X:\n----\n$result\n"
        }
    }

    return $txt
}

proc org_fld_text {} {
    global TkGnats tcl_platform
    return $TkGnats(ORGANIZATION)
}

#################################

if {"$TkGnats(LogName)" == "root"} {
    Msg "You cannot send problem reports as root.\n" "Please use your own login."
    Exit 1
}

# Set Create Defaults
####foreach d { {Class sw-bug} {Priority medium} {Severity serious} {Confidential no} }
foreach d [list [eval list Class $TkGnats(ClassesList)] {Priority medium} {Severity serious} \
        {Confidential no}] {
    if {![info exists TkGnats(CreateDefault[lindex $d 0])]} {
        set TkGnats(CreateDefault[lindex $d 0]) [lindex $d 1]
    }
}

# List of entry widgets for traverse key binding
set Tksendpr(tlist) {}

set Tksendpr(singletextflds) {
    Originator
    Release
    Synopsis
    Reply-To
}

if {$TkGnats(ReleaseBased)} {
    lappend Tksendpr(singletextflds) Keywords $TkGnats(Quarter) Date-Required
}

#########

# Since we don't use send-pr, set this to the TkGnats version
#if {[catch {exec send-pr --version} Tksendpr(version)]} {
#    set Tksendpr(version) unknown
#}
if {[regexp "tkgnats-\[^ \]*" $TkGnats(tkgnats_version) ver]} {
    set Tksendpr(version) $ver
} {
    set Tksendpr(version) "Unknown TkGnats version"
}

frame   .mframe -borderwidth 1 -relief raised
pack    .mframe -side top -fill x

menubutton .mframe.file -text "File" -menu .mframe.file.m -underline 0
menu       .mframe.file.m
.mframe.file.m add command -label "Send"          -command send_report
.mframe.file.m add command -label "Send and Exit" -command send_report_and_exit
.mframe.file.m add separator
.mframe.file.m add command -label "Cancel"        -command cancel_report

menubutton .mframe.edit -text "Edit" -menu .mframe.edit.m -underline 0
menu       .mframe.edit.m
.mframe.edit.m add command -label "Fonts..." -command "edit_fonts"

pack .mframe.file .mframe.edit -side left

menubutton .mframe.help -text "Help" -menu .mframe.help.m -underline 0
menu       .mframe.help.m
.mframe.help.m add command -label "Overview" \
        -command "helpMsg Create_Overview"
.mframe.help.m add separator
.mframe.help.m add command -label "Field Definitions" \
        -command "helpMsg Field_Definitions"
.mframe.help.m add separator
.mframe.help.m add command -label "Radio Buttons (Class, etc)" \
        -command "helpMsg Create_Radio_Buttons"
.mframe.help.m add command -label "Listbox Selectors (Category, etc)" \
        -command "helpMsg Create_Listbox_Selectors"
.mframe.help.m add command -label "Entry Fields (Originator, etc)" \
        -command "helpMsg Create_Entry_Fields"
.mframe.help.m add command -label "Text Fields (Description, etc)" \
        -command "helpMsg Create_Text_Fields"
.mframe.help.m add separator
.mframe.help.m add command -label "View Configuration Variables" \
        -command "helpMsg TkGnats_Variables"
.mframe.help.m add separator
.mframe.help.m add command -label "About" \
        -command "helpMsg TkGnats_About"
pack .mframe.help -side right

frame   .action -borderwidth 1 -relief raised
pack    .action -side top -fill x -anchor w
#button  .action.cancel      -borderwidth 1 -text "Cancel"        -command cancel_report
button  .action.send        -borderwidth 1 -text "Send"          -command send_report
button  .action.sendandexit -borderwidth 1 -text "Send and Exit" -command send_report_and_exit
#pack    .action.send .action.sendandexit .action.cancel -side left -padx 0
pack    .action.send .action.sendandexit -side left -padx 0

message .action.msg -aspect 10000 -relief sunken -bd 1 -text ""
pack    .action.msg -side left -fill x -expand 1

frame .eflds
radiobar_frame .eflds .eflds.lb

#####radiobar     .eflds.lb class        Class        {sw-bug doc-bug change-request support} None
radiobar     .eflds.lb class        Class        $TkGnats(ClassesList) None
radiobar     .eflds.lb priority     Priority     {low medium high} None
radiobar     .eflds.lb severity     Severity     {non-critical serious critical} None
radiobar     .eflds.lb confidential Confidential {no yes} None
radiobar_set .eflds.lb class        $TkGnats(CreateDefaultClass)
radiobar_set .eflds.lb priority     $TkGnats(CreateDefaultPriority)
radiobar_set .eflds.lb severity     $TkGnats(CreateDefaultSeverity)
radiobar_set .eflds.lb confidential $TkGnats(CreateDefaultConfidential)
pack .eflds.lb -side left
pack .eflds    -side top  -fill x -anchor w

frame .eboxs
frame .eboxs.clb
snd_category_listbox  .eboxs.clb $TkGnats(CategoryList)
frame .eboxs.slb
snd_submitter_listbox .eboxs.slb $TkGnats(SubmitterList)
pack .eboxs.clb .eboxs.slb -side top -anchor w -pady 2
pack .eboxs -side top -fill x -anchor w -pady 2

set Submitter $TkGnats(SUBMITTER)

if {[info exists  TkGnats(CreateDefaultCategory)]} {
    set Category $TkGnats(CreateDefaultCategory)
}

lappend Tksendpr(tlist) [singletext . Originator 80 "$TkGnats(FullName)" 14]
lappend Tksendpr(tlist) [singletext . Reply-To   80 "$TkGnats(EmailAddr)" 14]
lappend Tksendpr(tlist) [singletext . Release    80 "" 14]
lappend Tksendpr(tlist) [singletext . Synopsis   80 "" 14]

if {$TkGnats(ReleaseBased)} {
    lappend Tksendpr(tlist) [singletext . Keywords          80 "" 14]
    lappend Tksendpr(tlist) [singletext . $TkGnats(Quarter) 80 "" 14]
    lappend Tksendpr(tlist) [singletext . Date-Required     40 "" 14]
}

set Tksendpr(multitextflds) {
    >Description
    >How-To-Repeat
    >Environment
    >Organization
    >Fix
}

foreach tag $Tksendpr(multitextflds) {
    set frm($tag) ""
}

set frm(>Environment)  [env_fld_text]
set frm(>Organization) [org_fld_text]
set current_multi_text ""

lappend Tksendpr(tlist) [make_txt_mb $Tksendpr(multitextflds)]
switch_txt  ">Description" $Tksendpr(multitextflds)

set_text_traversal $Tksendpr(tlist)

#frame  .action -borderwidth 3
#button .action.cancel      -borderwidth 2 -text "Cancel"        -command cancel_report
#button .action.send        -borderwidth 2 -text "Send"          -command send_report
#button .action.sendandexit -borderwidth 2 -text "Send and Exit" -command send_report_and_exit
#
#pack .action.send .action.sendandexit .action.cancel -side left -padx 10
#
#pack .action -side top

###wm title      . "TkGnats - Create Problem Report"
wm title      . "TkGnats - [lindex $TkGnats(ServerInfo) 0] - $TkGnats(GNATS_ADDR)"
wm iconbitmap . @$TkGnats(lib)/tksendpr.xbm
wm iconname   . "$TkGnats(LogName)'s tksendpr"
