# 
#  Copyright (c) 1994-1998 A & A Custom Software.
#  All rights reserved.
# 
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#  3. All advertising materials mentioning features or use of this software
#     must display the following acknowledgement:
#       This product includes software developed by A & A Custom Software 
#       and its contributors.
#  4. Neither the name of A & A Custom Software nor the names of its 
#     contributors may be used to endorse or promote products derived from this 
#     software without specific prior written permission.
# 
#  THIS SOFTWARE IS PROVIDED BY A & A CUSTOM SOFTWARE AND CONTRIBUTORS ``AS IS''
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED.  IN NO EVENT SHALL A & A CUSTOM SOFTWARE OR CONTRIBUTORS BE 
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
#  POSSIBILITY OF SUCH DAMAGE.
# 
# $Id: rolodex.t,v 1.1.1.1 1998/01/04 22:47:29 abm Exp $
#

proc initRolodex { args } {

    global Th_Info
    global env

    set nlen $Th_Info(nlen)
    set clen $Th_Info(clen)
    set plen $Th_Info(plen)
    set Th_Info(style) \
        "%-${nlen}.${nlen}s  %-${clen}.${clen}s  %-${plen}.${plen}s"

    # Where to find the local database of fax numbers. FAXNUMBERS is
    # a fully qualified pathname of a file. E.g. "./tkhylafax/faxnumbers"
    if {[info exists env(FAXNUMBERS)]} {
        set Th_Info(phonedb) $env(FAXNUMBERS) 
        if {![file exists $Th_Info(phonedb)]} {
            set in [open $Th_Info(phonedb) {CREAT WRONLY}]
            close $in
        }
    } else {
        set Th_Info(phonedb) {}
    }
}

#
# Make a rolodex-like window for user to choose a fax number.
#

proc rolodex { top } {

    global Th_Info
    global phonelist

    # If the cache was not initialized, initialize it.
    if {[checkCacheDB $Th_Info(phonedb) phonelist]} {
	return
    }

    set t [mkToplevel $top {Fax Numbers}] 
    set hdr [format "$Th_Info(style)" "Name" "Company" "Phone"]
    set list [mkFrame $t list {-side top -fill both}]
    set oper [mkFrame $t oper {-side bottom -fill x}]
    set lb [mkLabeledListbox $t $hdr -selectmode browse]
    mkButton $oper rescan {-side left} -text Rescan -command "rescanRolodex $lb"
    mkButton $oper search {-side left} -text Search \
        -command "searchEntries -listbox $lb"
    mkButton $oper add {-side left} -text {Add to Batch} \
        -command "loadBatch $lb"
    mkButton $oper load {-side left} -text {Load Cover Sheet} \
        -command "loadCover $lb"
    mkButton $oper remove {-side left} -text {Remove from Rolodex} \
        -command "removeEntry $lb"
    mkButton $oper dismiss {-side left} -text Dismiss -command "destroy $t"

    loadRolodex $lb
}

proc loadRolodex { lb } {

    global Th_Info
    global phonelist

    set l [lsort [array names phonelist]]
    foreach i $l {
	set company [lindex $phonelist($i) 0]
	set phone [lindex $phonelist($i) 1]
	set entry [format "$Th_Info(style)" $i $company $phone]
	$lb insert end $entry
    }
}

proc removeEntry { lb } {

    global Th_Info
    global phonelist

    set idx [$lb curselection]
    if {$idx == ""} {
	return
    }
    set entry [$lb get $idx]
    set name [extractName $entry]

    unset "phonelist($name)"
    
    # Update database on disk
    updateDB $Th_Info(phonedb) phonelist

    # Show updated fax database
    $lb delete $idx 
}

proc deleteEntry { args } {

    global Th_Info
    global phonelist

    if {$Th_Info(name) == ""} {
        tk_dialog .err "Ooops!" "Recipient name is empty" error 0 "OK"
        return
    }
    set res [tk_dialog .err "Confirm" "Delete entry $Th_Info(name) from \
	    rolodex?" questhead 0 "OK" "Abort"] 
    if {$res != "0"} {
        return
    }

    unset "phonelist($Th_Info(name))"
    
    # Update database on disk
    updateDB $Th_Info(phonedb) phonelist
}

proc loadBatch { lb } {

    global Th_Info

    set idx [$lb curselection]
    if {$idx == ""} {
	return
    }
    set entry [$lb get $idx]

    # Make batch phone number list
    lappend Th_Info(batchDest) $entry

    # Remove highlight
    $lb select clear 0 end

    # Update the batch listbox 
    if {[info exists Th_Info(viewBatch)] && 
        [winfo exists $Th_Info(viewBatch)]} {
	$Th_Info(viewBatch) insert end $entry
    }
}

proc rescanRolodex { lb } {

    global phonelist
    global Th_Info

    # If the cache was not initialized, initialize it.
    if {[checkCacheDB $Th_Info(phonedb) phonelist]} {
	return
    }

    # Remove whats already in the listbox
    $lb delete 0 end

    loadRolodex $lb
}

proc loadCover { lb } {

    global Th_Info

    set idx [$lb curselection]
    if {$idx == ""} {
	return
    }
    set entry [$lb get $idx]
    # Extract the name, company and phone from the selected item.
    set Th_Info(name) [extractName $entry] 
    set Th_Info(company) [extractCompany $entry] 
    set Th_Info(phone) [extractPhone $entry] 

    # Remove highlight
    $lb select clear 0 end
}

#
# Given the filename and array of data, check if the database cache
# is initialized and if not load it from disk.
#

proc checkCacheDB { filename data } {

    upvar $data z

    if {[array size z] == 0} {
        if {[file isfile $filename]} {
            ro $filename z
        } else {
            tk_dialog .err "Ooops!" "Path for this rolodex is not set. \
            See the man page for more information." warning 0 OK
            return 1
        }
    }
    return 0
}

#
# Given the filename and array of data, write information to disk
# in the form tag=value.
#

proc updateDB { filename data } {

    upvar $data z

    set f [open $filename {CREAT WRONLY TRUNC}]
    set names [array names z]
    foreach n $names {
        puts $f "$n=$z($n)"
    }
    close $f

}

#
# Add/Modify entry in the fax numbers database.
#

proc  updateRolodex { args } {

    global phonelist
    global Th_Info

    if {$Th_Info(name) == ""} {
        tk_dialog .err "Ooops!" "Recipient name is empty" error 0 "OK"
        return
    }

    # If the cache was not initialized, initialize it.
    if {[checkCacheDB $Th_Info(phonedb) phonelist]} {
        return
    }

    # Update the fax number database cache
    set name [string trim $Th_Info(name)] 
    set company $Th_Info(company) 
    set phone $Th_Info(phone) 
    if {[info exists phonelist($name)]} {
        set res [tk_dialog .err "Ooops!" "This name already exists in the \
	        rolodex. \n\n Overwrite existing entry?" questhead 0 "OK" \
	        "Abort"] 
        if {$res != "0"} {
	   return
        }
    }
    set "phonelist($name)" [list $company $phone]

    # Update database on disk 
    updateDB $Th_Info(phonedb) phonelist
}
