local Class = require "luanode.class"
local EventEmitter = require "luanode.event_emitter"
local Http = require "luanode.http"
local XHR = require "socket-io-client.transports.xhr"

local XHRPolling = Class.InheritsFrom(XHR)
XHRPolling.type = "xhr-polling"

function XHRPolling.check()
	return true
end

---
--
function XHRPolling:__init (base, options)
	local new = Class.construct(XHRPolling, base, options)

	return new
end

---
--
function XHRPolling:connect ()
	--console.log("XHRPolling:connect")

	self:_get()
	return self
end

---
--
function XHRPolling:_get ()
	--console.log("XHRPolling:_get")

	local req, url_path = self:_request(os.time(), "get")
	self._xhr = req

	req:on("response", function(_, res)
		
		res:on("data", function(_, chunk)
			res._body = res._body or {}
			table.insert(res._body, chunk)
		end)

		res:on("end", function()
			if res._body then
				res._body = table.concat(res._body, "")
			else
				res._body = ""
			end
			if res.statusCode ~= 200 then
				local msg = console.warn("%s request for url '%s' failed with status %s => Body: '%s'", 
					req.method, url_path, res.statusCode, res._body)
				--callback("Wrong HTTP response")
				self:_onDisconnect()
			else
				--console.log(res._body)
				self:_onData(res._body)
				self:_get()
			end
			--client:removeListener("error", errorListener)
		end)
	end)

	req:finish("")
end

return XHRPolling
