note
	description: "Summary description for {DOWNLOADER}."
	author: ""
	date: "$Date$"
	revision: "$Revision$"

class
	DOWNLOADER
create
	make

feature{NONE}
	executor : separate CANCELLABLE_EXECUTOR
	token : separate CANCELLATION_REQUEST
feature
	url: detachable STRING
	download_cancelled : EVENT_TYPE[TUPLE]
	download_completed : EVENT_TYPE[TUPLE]
	download_progress_changed : EVENT_TYPE[TUPLE[INTEGER, INTEGER]]

	make
	local
	do
		create token.empty
		create executor.make

		subscribe_executor (executor)

		create download_completed
		create download_progress_changed
		create download_cancelled
	end

	download_async
	require
		url /= void
	do
		start_download (executor)
	end

	cancel
	do
		cancel_token(token)
	end

	set_url(a_url: separate STRING)
	do
		url := create {STRING}.make_from_separate(a_url)
	end

feature{NONE}



	start_download(a_executor : separate CANCELLABLE_EXECUTOR)
	require
		url /= void
	local
		new_token : separate CANCELLATION_REQUEST
		a_unit : separate DOWNLOADER_UNIT
		l_url : separate STRING
	do
		create new_token.make
		token := new_token
		create l_url.make_empty

		if attached {STRING} url as sep_url then
			l_url :=  sep_url
		end

		create a_unit.make(l_url)
		subscribe_unit(a_unit)

		a_executor.set_new_token(token)
		a_executor.run(a_unit)
	end

	cancel_token(a_token : separate CANCELLATION_REQUEST)
	do
		a_token.request_cancellation
	end

	subscribe_unit(a_unit : separate DOWNLOADER_UNIT)
	do
		a_unit.execution_progress_changed.subscribe (agent on_progress)
	end

	subscribe_executor(a_executor : separate CANCELLABLE_EXECUTOR)
	do
		a_executor.execution_cancelled.subscribe (agent on_cancelled)
		a_executor.execution_completed.subscribe (agent on_completed)
	end

	on_cancelled
	do
		download_cancelled.publish ([])
	end

	on_completed
	do
		download_completed.publish ([])
	end
	on_progress(a, b :INTEGER)
	do
		download_progress_changed.publish ([a, b])
	end


end
