 
 	upload: (url, form, callback) -> # support auto-relogin relavant url
 		url = @url url
-		if not @id # TODO: check login properly
-			@auto_login (result) =>
-				@http_upload url, form, callback
-		else
+		@login_check =>
+			# TODO: check response for session timeout
 			@http_upload url, form, callback
 
 	init: (callback) ->


	add_bt_task_by_info_hash: (hash, callback) ->
		hash = hash.toUpperCase()
		# TODO: check session and @id
		if @id
			url = "http://dynamic.cloud.vip.xunlei.com/interface/get_torrent?userid=#{@id}&infoid=#{hash}"
			@add_bt_task_by_query_url url, callback
		else
			# TODO: ineffient, should try login_enrich_cookie
			@auto_login =>
				url = "http://dynamic.cloud.vip.xunlei.com/interface/get_torrent?userid=#{@id}&infoid=#{hash}"
				@add_bt_task_by_query_url url, callback

	add_magnet_task: (url, callback) ->
		# TODO: check session and @id
#		@add_bt_task_by_query_url url, callback
		if @id
			@add_bt_task_by_query_url url, callback
		else
			@auto_login =>
				@add_bt_task_by_query_url url, callback

	add_task: (url, callback) ->
		throw new Error("Not Implemented: add_task")

					@password = password
					@auto_login callback


	login_check: (callback) ->
#		if @get_cookie('.xunlei.com', 'sessionid')
#			throw new Error("Not Implemented: login_check")
#		else if @get_cookie '.xunlei.com', 'lsessionid'
#			@login_enrich_cookie (result) =>
#				if result.ok
#					callback result
#				else
#					callback ok: false
#		else
#			callback ok: false, reason: 'No session found'
		if not (@get_cookie('xunlei.com', 'userid') and @get_cookie('.xunlei.com', 'sessionid'))
			@login_enrich_cookie (result) =>
				if result.ok
					callback result
				else
					if @auto_relogin
						@auto_login (result) =>
							callback result
					else
						callback ok: false, reason: 'auto-relogin is disabled'
		else
			callback ok: true

	# TODO:
	auto_relogin_for: ({url, form, pattern, callback}) ->
		if form?
			request = (callback) => @post url, form, callback
		else
			request = (callback) => @get url, callback
		if Object.prototype.toString.call(pattern) == '[object RegExp]'
			is_timeout = (text) -> pattern.match text
		else
			is_timeout = (text) -> text == pattern
		relogin = =>
			@auto_login (result) =>
				if result.ok
					request (result) =>
						callback result
				else
					callback result
		start = =>
			request (result) =>
				{text} = result
				if is_timeout(text) and @auto_relogin
					relogin()
				else
					callback result
		@login_check =>
			start()

	with_id: (callback) ->
		@login_check =>
			callback @get_id_from_cookie()

	#######
	# add #
