local z={}z.__index=z function z.new(A,Y)return setmetatable({Stream=A,Connected=false,_handler=Y},z)end function z.Disconnect(z)for A,Y in pairs(z.Stream._connections)do if Y==z then table.remove(z.Stream._connections,A)return end end if#z.Stream._connections==0 then z.Stream:_unsubscribe()end end local A={}A.__index=A function A.new(z,Y)return setmetatable({Streams=z;Name=Y;Subscribed=false;_connections={}},A)end function A._subscribe(z)if not z.Subscribed then return z.Streams.CmdrAdditions.Network:Request("\083\116\114\101\097\109\083\117\098\115\099\114\105\098\101",z.Name)end end function A._unsubscribe(z)if z.Subscribed then return z.Streams.CmdrAdditions.Network:Request("\083\116\114\101\097\109\085\110\115\117\098\115\099\114\105\098\101",z.Name)end end function A._emit(A,z)for A,Y in pairs(A._connections)do Y._handler(z)end end function A.FetchHistory(z)return z.Streams.CmdrAdditions.Network:Request("\083\116\114\101\097\109\071\101\116\072\105\115\116\111\114\121",z.Name)end function A.Connect(Y,A)if#Y._connections==0 then Y:_subscribe()end local m=z.new(Y,A)table.insert(Y._connections,m)return m end return A
local Connection = {}
Connection.__index = Connection

function Connection.new(stream, handler)
	return setmetatable({
		Stream = stream,
		Connected = false,
		_handler = handler
	}, Connection)
end

function Connection:Disconnect()
	for index, connection in pairs(self.Stream._connections) do
		if connection == self then
			table.remove(self.Stream._connections, index)
			return
		end
	end

	if #self.Stream._connections == 0 then
		self.Stream:_unsubscribe()
	end
end

local Stream = {}
Stream.__index = Stream

function Stream.new(streams, name)
	return setmetatable({
		Streams = streams,
		Name = name,
		Subscribed = false,
		_connections = {}
	}, Stream)
end

function Stream:_subscribe()
	if not self.Subscribed then
		return self.Streams.CmdrAdditions.Network:Request("StreamSubscribe", self.Name)
	end
end

function Stream:_unsubscribe()
	if self.Subscribed then
		return self.Streams.CmdrAdditions.Network:Request("StreamUnsubscribe", self.Name)
	end
end

function Stream:_emit(event)
	for _, connection in pairs(self._connections) do
		connection._handler(event)
	end
end

function Stream:FetchHistory()
	return self.Streams.CmdrAdditions.Network:Request("StreamGetHistory", self.Name)
end

function Stream:Connect(handler)
	if #self._connections == 0 then
		self:_subscribe()
	end

	local connection = Connection.new(self, handler)
	table.insert(self._connections, connection)
	return connection
end

return Stream