# Save, open Tkabber sessions
#############################################################################
#
# Session is a list of {priority user server resource script}
#

namespace eval session {
    variable session_file [file join $::configdir session.tcl]
}

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

proc session::save_session {} {
    variable session_file

    set session {}
    hook::run save_session_hook session

    set fd [open $session_file w]
    fconfigure $fd -encoding utf-8
    puts $fd $session
    close $fd
}

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

proc session::save_session_on_exit {} {
	save_session
}

hook::add quit_hook [namespace current]::session::save_session_on_exit

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

proc session::open_session {} {
    variable session_file

    set session_script_list {}
    catch {
	set fd [open $session_file r]
	fconfigure $fd -encoding utf-8
	set session_script_list [read $fd]
	close $fd
    }

    foreach script [lsort -integer -index 0 $session_script_list] {
	lassign $script priority user server resource command

	if {($user != "") || ($server != "") || ($resource != "")} {
	    # HACK. It works if called before any JID is connected
	    set connid [jlib::new -user $user \
				  -server $server \
				  -resource $resource]
	} else {
	    set connid ""
	}

	after idle [list eval $command [list $connid $user@$server/$resource]]
    }
}

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

proc session::open_session_on_start {} {
	open_session
	after 60 [namespace current]::save_session_timeout
}

proc session::save_session_timeout {} {
	save_session
	after 60 [namespace current]::save_session_timeout
}

hook::add finload_hook [namespace current]::session::open_session_on_start 90

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


