# Copyright (c) 1993 by Sanjay Ghemawat
###############################################################################
# Calendar IO

# effects - Create thread that periodically performs required IO.
proc io_thread {} {
    io_checks
    after 15000 io_thread
}

# effects - Perform IO checks.
proc io_checks {} {
    trigger fire save
    foreach file [calendar_filenames] {
	io_check $file
    }
}

# effects - Perform IO checks on specified calendar.
#	    Returns true iff new items were read.
proc io_check {calendar} {
    set stale [cal stale $calendar]
    set dirty [cal dirty $calendar]

    if {!$stale && !$dirty} {return}

    if {$stale && !$dirty} {
	trigger fire exclude $calendar
	if [catch {cal reread $calendar} result] {
	    error_notify "" "$calendar\n\n$result"
	}
	trigger fire include $calendar
	return
    }

    if {!$stale && $dirty} {
	if [catch {cal save $calendar} result] {
	    error_notify "" "$calendar\n\n$result"
	}
	return
    }

    if {$stale && $dirty} {
	set result [yes_or_no	""\
				"Conflicting changes to $calendar"\
				"Read from disk"\
				"Overwrite"]
	if {$result} {
	    # Discard local changes
	    trigger fire exclude $calendar
	    if [catch {cal reread $calendar} result] {
		error_notify "" "$calendar\n\n$result"
	    }
	    trigger fire include $calendar
	}

	# Overwrite other changes
	if [catch {cal save $calendar} result] {
	    error_notify "" "$calendar\n\n$result"
	}
	return 0
    }
}
