# Copyright (c) 1993 by Sanjay Ghemawat
##############################################################################
# Various Support Routines

# Initialization
set ical_state(views)	{}
set ical_state(view)	{}
set ical_state(clip)	{}
set ical_state(selview)	{}
set ical_state(selitem)	{}
set ical_state(seliw)	{}

proc support_init {} {
    global month_name
    catch {unset month_name}

    set month_name(1)	January
    set month_name(2)	February
    set month_name(3)	March
    set month_name(4)	April
    set month_name(5)	May
    set month_name(6)	June
    set month_name(7)	July
    set month_name(8)	August
    set month_name(9)	September
    set month_name(10)	October
    set month_name(11)	November
    set month_name(12)	December

    global weekday_name
    catch {unset weekday_name}

    set weekday_name(1)	Sunday
    set weekday_name(2)	Monday
    set weekday_name(3)	Tuesday
    set weekday_name(4)	Wednesday
    set weekday_name(5)	Thursday
    set weekday_name(6)	Friday
    set weekday_name(7)	Saturday

    # Parse arguments
    ical_parse_args
    if [string compare [info commands tk] ""] {
	# Parse tk arguments before calculating preferences
	ical_parse_tk_args

	# Handle preferences before user code gets loaded.
	Preference-with-name pref

	# Remove default window
	wm withdraw .
    }

    # Hooks
    create-hook ical-startup
    create-hook ical-exit

    create-hook item-create
    create-hook alarm-fire

    create-hook dayview-startup
    create-hook dayview-close
    create-hook	dayview-focus
    create-hook dayview-unfocus
    create-hook dayview-set-date

    # Load various customization files
    global ical
    ical_load_file $ical(libparent)/site.tcl
    ical_load_file $ical(library)/site.tcl
    ical_load_file ~/.tk/ical/user.tcl

    run-hook ical-startup
}

proc ical_load_file {name} {
    # See if the file exists.  We wrap the "file exists ..." command
    # inside a "catch" to handle errors generated by tilde expansion.
    set e 0
    catch {set e [file exists $name]}
    if $e {
	if [catch {uplevel #0 [list source $name]} msg] {
	    error_notify "" "Error loading \"$name\"\n\n$msg"
	}
    }
}

proc ical_filenames {} {
    set list ""
    lappend list [cal main]
    cal forincludes x {
	lappend list $x
    }
    return $list
}

# Return title for calendar file name
proc ical_title {calendar} {
    # First look in calendar itself
    if ![catch {set title [cal option -calendar $calendar Title]}] {
	return $title
    }

    # No title in calendar:  Generate title from file name.
    if ![string compare $calendar [cal main]] {
	return "Main Calendar"
    } else {
	return [file tail $calendar]
    }
}

# effects - If listName contains specified string, remove it from the list
#	    and return 1.  Else return 0.

proc lremove {listName string} {
    upvar $listName list

    set i [lsearch -exact $list $string]
    if {$i >= 0} {
	set list [lreplace $list $i $i]
	return 1
    } else {
	return 0
    }
}

# requires - item occurs on date.  leader is either "" or a top-level window.
# effects -  If item does not repeat, return "unnecessary".
#
#	     If item repeats, but user interaction says it is ok to
#	     modify all items, return "ok".
#
#	     If item repeats, but user interaction says it is ok to
#	     modify this instance, split item up so that modifications
#	     will only happen to the instance on date, and return "instance".
#
#	     If item repeats, and user interaction cancels the current
#	     operation, return "cancel".

set ical_state(last) {}
set ical_state(modifylast) 0

proc repeat_check {leader item date} {
    global ical_state
    set last $ical_state(last)
    set lastmod $ical_state(modifylast)
    set ical_state(last) $item
    set ical_state(modifylast) 0

    # Nothing to check if item does not repeat
    if ![$item repeats] {return "unnecessary"}

    # See if user already said it was okay to modify this item
    if {![string compare $item $last] && $lastmod} {
	set ical_state(modifylast) 1
	return "unnecessary"
    }

    set result [yes_no_cancel $leader\
		"This item repeats.  Should all occurrences be changed?"\
		"Yes" "Just this one" "Cancel"]

    if {$result == "cancel"} {return "cancel"}
    if {$result == "yes"} {
	set ical_state(modifylast) 1
	return "ok"
    }

    # Split item into two items.  One item only occurs on this
    # date.  The other item covers the rest of the occurrences.

    set copy [$item clone]
    $copy deleteon $date
    $item date $date

    cal add $copy [$item calendar]

    return "instance"
}

# effects - Print usage message and exist
proc ical_usage {} {
    puts stderr {Usage: ical [options]
          -calendar <file>              ; Calendar file
          -list                         ; List imminent items
          -show +days                   ; Like "-list" but covers more days
    If on X display --
          -iconic                       ; Start iconified
          -iconposition <x,y>           ; Initial icon position
          -mono                         ; Do not use colors even if available
          -popup                        ; Just display imminent items
          -fg <color>                   ; Foreground color
          -bg <color>                   ; Background color
          -geometry <geometry>          ; Initial window geometry}
    exit 1
}

# effects - Parse some standard arguments
proc ical_parse_args {} {
    global argv ical
    set mono 0

    set oldargv $argv
    set argv {}
    while {[llength $oldargv] > 0} {
	set arg [lindex $oldargv 0]
	set oldargv [lrange $oldargv 1 end]

	if {![string compare $arg "-calendar"] && ([llength $oldargv] >= 1)} {
	    set ical(calendar) [lindex $oldargv 0]
	    set oldargv [lrange $oldargv 1 end]
	    continue
	}

	lappend argv $arg
    }
}

# effects - Parse some standard Tk arguments
proc ical_parse_tk_args {} {
    global argv ical

    set oldargv $argv
    set argv {}
    while {[llength $oldargv] > 0} {
	set arg [lindex $oldargv 0]
	set oldargv [lrange $oldargv 1 end]

	if {![string compare $arg "-iconic"]} {
	    set ical(iconic) 1
	    continue
	}

	if {![string compare $arg "-mono"]} {
	    tk colormodel . mono
	    continue
	}

	if {![string compare $arg "-iconposition"] && ([llength $oldargv] >= 1)} {
	    if ![scan [lindex $oldargv 0] "%d,%d" x y] {ical_usage}
	    set ical(iconposition) [list $x $y]
	    set oldargv [lrange $oldargv 1 end]
	    continue
	}

	if {![string compare $arg "-bg"] && ([llength $oldargv] >= 1)} {
	    lappend ical(prefs) "option add *Background [lindex $oldargv 0]"
	    set oldargv [lrange $oldargv 1 end]
	    continue
	}

	if {![string compare $arg "-fg"] && ([llength $oldargv] >= 1)} {
	    lappend ical(prefs) "option add *Foreground [lindex $oldargv 0]"
	    set oldargv [lrange $oldargv 1 end]
	    continue
	}

	lappend argv $arg
    }
}
