#!/usr/local/qddb/bin/qwish -f
#
# inventory_delete.tcl --
#     This module was created to provide a window so the user
#     could delete multiple inventory items with ease.


#
# Maintenance Class --
#     The Maintenance class simply provides a window that
#     is populated with results from a Qddb search on user
#     specified search criteria.  The results are thrown
#     into a listbox from which the user can multiply select inventory items
#     for deletion.  In addition, there are two buttons that
#     "Mark all for deletion" and "Mark all for keep" to
#     toggle the found rows for deleting/keeping.
#     
set tcl_precision 17
itcl_class Maintenance {
    constructor {config} {
	global DragDrop fx_config_dir _res
	wm title . $title
	wm withdraw .
	if {[catch "qddb_schema open Inventory" s] != 0} {
	    tk_dialog .dialog "Inventory" "Unable to open Schema" info 0 Ok
	}
	set fx_config_dir .inv_convig
	Fx:Init $s
	Fx_Menubar menubar -w .mb -schema $s -array gv_myattr \
		-config_dir .inv_config \
		-afteraddmode {wm title . "Inventory: <Add Mode>"} \
		-aftersearchmode  {wm title . "Inventory: <Search Mode>"} \
		-afterchangemode  [list $this afterchangemode] \
		-aftersearch [list $this afterSearch] \
		-search_results 0
	set gv_search_entry [menubar SearchForEntry]
	frame .f1 -relief groove -bd 4
	frame .f1.mp
	frame .f1.d 
	Fx_Entry mfr  -w .f1.mp.mfr  -attr Mfr -setschema $s -mandatory 1 \
		-searchfor_entry $gv_search_entry 
	Fx_Entry part -w .f1.mp.part -attr PartNumber -mandatory 1
	Fx_Entry desc -w .f1.d.desc  -attr Description
	pack forget .f1.mp.mfr .f1.mp.part .f1.description
	pack .f1         -side top -fill x -expand yes
	pack .f1.mp      -side top -fill x -expand yes
	pack .f1.d       -side top -fill x -expand yes
	pack .f1.mp.mfr  -side left -fill x -expand yes
	pack .f1.mp.part -side left
	pack .f1.d.desc  -side left
	.f1.mp.mfr.f_0.l  configure -text "Manufacturer/Part#:" -width $lwidth
	.f1.mp.part.f_0.l configure -bitmap @$bitmapdir/bluedot.xpm
	.f1.d.desc.f_0.l  configure -text "Description:" -width $lwidth

	frame .f2 -relief groove -bd 4
	frame .f2.show
	pack .f2 -side top -fill x -expand yes
	pack .f2.show -side top -fill x -expand yes
	button .f2.show.a -text "Mark All Delete" \
		-command [list $this markAllDelete] -fg blue
	button .f2.show.b -text "Mark All Keep" \
		-command [list $this markAllKeep] -fg blue
	button .f2.show.c -text "Delete" -command [list $this doDelete] -fg blue
	pack .f2.show.a -side left
	pack .f2.show.b -side left -padx 2m
	pack .f2.show.c -side right

	set f .f2.lbox
	set _w $f
	set widths2 { 6 14 8 30 }
	set headings { Delete Manufacturer {Part #} Description }
	set alignment { left left left left left }
	set separators { {} {} {} {} {} }
	set _res {}
	frame $f
	pack $f -side bottom -fill x
	Fx_MultiColumnListBox _search_results -w $_w.f -widths $widths2 \
		-headings $headings -numcols [llength $headings] \
		-align $alignment \
		-width 150 \
		-exportselection off \
		-separators $separators \
		-single_select on \
		-height 20 \
		-onselect [list $this toggleDelete]
#	bind $f <FocusIn> {_search_results FocusSelect}
	menubar configure -instances [Fx_Entry :: GetInstances] \
		-frames [Fx_Frame :: GetInstances]
	menubar SearchModeProc
	wm deiconify .
    }
    method toggleDelete {str} {
	set r [_search_results GetRow $str]
	if {[lindex $r 0] == "Yes"} {
	    set new [concat "---" [string range $r 3 end]]
	} else {
	    set new [concat Yes [string range $r 3 end]]
	}
	_search_results ReplaceAndFormatRow $str $new
    }
    method markAllDelete {} {
	blt_busy hold .
	update idletasks
	set contents [_search_results GetContents]
	set row_count 0
	foreach i $contents {
	    if {[lindex $i 0] == "---"} {
		set new_row [concat Yes [string range $i 3 end]]
		_search_results ReplaceAndFormatRow $row_count $new_row
	    }
	    incr row_count
	}
	blt_busy forget .
    }
    method markAllKeep {} {
	blt_busy hold .
	update idletasks
	set contents [_search_results GetContents]
	set row_count 0
	foreach i $contents {
	    if {[lindex $i 0] == "Yes"} {
		set new_row [concat --- [string range $i 3 end]]
		_search_results ReplaceAndFormatRow $row_count $new_row
	    }
	    incr row_count
	}
	blt_busy forget .
    }
    method doDelete {} {
	global carr
	set reply [tk_dialog .dialog "Confirm Inventory Delete" \
	"Choosing Ok will delete all inventory items marked for deletion, Are you sure?" info 0 Ok Cancel]
	if { $reply == 1 } { return }
	set contents [_search_results GetContents]
	set count 0
	set ErrorStaleParts {}
	set ErrorLockedParts {}
	set ErrorInStock {}
	foreach i $contents {
	    if {[lindex $i 0] == "Yes"} {
		set part [lindex $i 2]
		set k [qddb_search $s -prunebyattr PartNumber word $part]
		set k1 [qddb_keylist get $k]
		set t [isUniqueTuple $k1 $s]
		if { $t == "" } {

		    # Record not in inventory database, so remove from listbox
		    # This stmt will only get executed if listbox becomes stale.
		    # Meaning, item is deleted in "Inventory" window without 
                    # updating the inventory_delete window

		    _search_results DeleteRow $count
		    lappend ErrorStaleParts $part
		    continue
		}
		if { [qddb_tuple lock $t] == 0 } {
		    # Record locked in other window, so don't delete it
		    lappend ErrorLockedParts $part
		    incr count
		    continue
		}
		set t_v [qddb_view define $t {
		    { PartNumber         carr(PartNumber) }
		    { QtyOnHand          carr(QtyOnHand) }}]
		if { $carr(QtyOnHand) != 0 } {
		    # Don't delete inventory item if there are parts on hand
		    lappend ErrorInStock $part
		    incr count
		    continue
		}
		# Once we get here, we've checked all exceptions, so delete the
		# record from inventory
		_search_results DeleteRow $count
		qddb_tuple remove $t
		qddb_keylist delete $k
		qddb_keylist delete $k1
	    } else {
		incr count
	    }
	}
	#
	# If errors, display dialog to tell user what happened.
	#
	set msg {}
	if { [llength $ErrorInStock] != 0 } {
	    lappend msg {The following parts have Qty on Hand and were *not* deleted:}
	    foreach i $ErrorInStock { lappend msg "     $i" }
	}
	if { [llength $ErrorLockedParts] != 0 } {
	    if {[llength $ErrorInStock] != 0} {
		lappend msg {};	lappend msg {}
	    }
	    lappend msg {The following parts were locked in another window and were *not* deleted:}
	    foreach i $ErrorLockedParts { lappend msg "     $i" }
	}
	if { [llength $ErrorStaleParts] != 0 } {
	    if {[llength $ErrorInStock] != 0 || [llength $ErrorLockedParts] != 0 } {
		lappend msg {};	lappend msg {}
	    }
	    lappend msg {The following parts were already deleted from another window:}
	    foreach i $ErrorStaleParts { lappend msg "     $i" }
	}
	if {[llength $msg] != 0} {
	    blt_busy hold .
	    MsgBox "Deletion Warnings" $msg errorBox
	    tkwait window .errorBox
	    blt_busy forget .
	}
    }
    method afterSearch {} {
	global _res fx:status_variable
	_search_results ClearContents
	if [menubar LastSearchWasNull] {
	    set r {}
	} else {
	    set r [menubar GetLastSearch]
	}
        set _res {}
	foreach i $r {
	    set line [qddb_rows getval {Mfr PartNumber Description} [lindex $i 1]]
	    set line [concat Yes $line]
	    lappend _res $line
	}
	_search_results ClearRows
	_search_results AppendRows $_res
	_search_results SortContents {}
	_search_results Format
	_search_results Display
	::set fx:status_variable [format "Rows found: %d" [llength $_res]]
    }
    method afterchangemode {} {
	global gv_myattr
	wm title . "Inventory: $gv_myattr(Mfr) \ $gv_myattr(PartNumber)"
    }
    method config {config} {}
    protected s
    protected _res
    protected _search_results

    public title "Inventory" {}
    public rootdir /usr/local/Qba/bin {}
    public bitmapdir /usr/local/Qba/bitmaps {}
    public fx_config_dir .inv_config {}
    public lwidth 28
}
lappend auto_path . $qddb_library/fx $blt_library $blt_library/dd_protocols \
	/usr/local/Qba/bin/library
Maintenance maintenance
