-- Load MQTT library
local mqtt = require("mqtt")
local client

local maxClientId = ...

local eventChannel = love.thread.getChannel("mqtt_event")
local commandChannel = love.thread.getChannel("mqtt_command")

local function call(target, ...)
	local args = {...}
	eventChannel:push {
		target = target,
		args = args
	}
end

local function onConnect(connack)
	print("On connect")
	call("connect", connack)
end

local function onMessage(message)
	if message.topic:sub(0, 7) == "spider/" then
		message.topic = message.topic:sub(8)
	end
	print(message.topic)
	call("message2", message.topic, message.payload)
end

local function onCommand(command)
	if command.command == "send" then
		client:publish {
			topic = "spider/" .. command.topic,
			payload = command.arg,
			qos = 0
		}
	elseif command.command == "subscribe" then
		local topic = "spider/" .. command.topic
		assert(client:subscribe {
			topic = topic
		})
		print("Subscribed to " .. topic)
		print("Subscribed to " .. topic)
	end
end

local function main()
	client = mqtt.client {
		uri = "mqtt.seeseepuff.be",
		id = "mqtt_controller-" .. math.random(0, maxClientId),
		clean = true,
		reconnect = 5,
	}

	client:on {
		connect = onConnect,
		message = onMessage,
		error = function(message)
			print("MQTT error: " .. message)
			call("onError", message)
		end
	}

	print("Connecting")
	local ioloop = mqtt.get_ioloop()
	local i = 0
	ioloop:add(function()
		local command = commandChannel:pop()
		if command then
			onCommand(command)
		end
	end)
	mqtt.run_ioloop(client)
end

main()
