#! /bin/env tclsh

package require http

package require {ycl coro relay}
namespace import [yclprefix]::coro::relay

namespace eval doc {}

coroutine geturl apply [list {} {
	while 1 {
		relay accept {deliver url}
		# Because this coroutine uses [yield] directly, [accept] only 1 order
		# should be made to it .
		coroutine geturl_[info cmdcount] apply [list {deliver url} {
			http::geturl $url -command [info coroutine]
			set token [yield]

			{*}$deliver [http::data $token]
		} [namespace current]] $deliver $url
	}
} [namespace current]]


variable doc::main {
	description {
		Retrieve each URL specified on the command line and print a dictionary
		mapping thee URL to its contents .
	}
}
coroutine main apply [list {argv0 argv} {
	set orders {}
	foreach url $argv {
		dict set orders [relay order [expr {1000 * [incr multiplier]}] geturl $url] $url
	}

	# Spend time on something
	after 5000 [list [info coroutine]]
	yield


	foreach unused [dict keys [relay pending]] {
		set result [relay receive]
		lappend results [dict get $orders [relay last]] $result
		dict unset orders [relay last]
	}
	# Cancel any outstanding orders
	puts [list cancelling orders $orders]
	relay cancel orders $orders 

	exit 0
}] $argv0 $argv

vwait forever
