# agent_meet
#
# Purpose: Meet with another agent
#

proc old_meet {dest_id {timeoutType -blocking} {timeoutPeriod {}}} glue {

    global agent errorCode errorInfo restrict

	# check the arguments

    if {$timeoutType == "-time"} {

	if {$timeoutPeriod == ""} {
	    return -code error -errorcode SYNTAX "\"-time\" option must be followed by the number of seconds"
	}

	if [catch {expr 0 + $timeoutPeriod}] {
	    return -code error -errorcode SYNTAX "invalid number of seconds \"$timeoutPeriod\": must be a real number"
	}

	if {$timeoutPeriod < 0} {
	    return -code error -errorcode SYNTAX "invalid number of seconds \"$timeoutPeriod\": can not be negative"
	}

    } elseif {$timeoutType != "-blocking"} {

	return -code error -errorcode SYNTAX "unknown option \"$timeoutType\": should be -time or -blocking"
    }

	# request the meeting

    if {$timeoutType == "-time"} {

        set endTime [expr $restrict(wall-current) + $timeoutPeriod]
	set handle [request_meeting $dest_id -time $timeoutPeriod]

    } else {

	set handle [request_meeting $dest_id]
    }

	# catch all errors so that we can close the meeting if necessary

    if {[catch {

	while {1} {

	    if {$timeoutType == "-time"} {

	  	set timeoutPeriod [expr $endTime - $restrict(wall-current)]

		if {$timeoutPeriod < 0} {
		    set timeoutPeriod 0
		}

		set result [agent_select $handle -time $timeoutPeriod]

		if {$result == ""} {
		    return -code error -errorcode TIMEOUT timeout
		}

	    } else {

		set result [agent_select $handle -blocking]
	    }

	    set hresult [lindex $result 0]
	    set status [lindex $hresult 1]

	    if {$status == "requested"} {
		accept_meeting $handle
	    } elseif {$status == "accepting"} {
		# nothing
	    } elseif {$status == "connecting"} {
		# nothing
	    } elseif {$status == "complete"} {
		break
	    } elseif {$status == "rejected"} {
		return -code error -errorcode FAILED "target agent rejected the meeting"
	    } else {
		return -code error -errorcode FAILED "meeting attempt failed during setup"
	    }
	}

    } result]} {    # error on CATCH

	catch {
	    meeting_close $handle
	}

	return -code error $result

    } else {        # no error on CATCH

	return $handle
    }
}
