local dirtylarry = require "dirtylarry/dirtylarry"

function init(self)
	msg.post(".", "acquire_input_focus")

	local logosize = 256
	local screen_width = sys.get_config("display.width", 600)
	local screen_height = sys.get_config("display.height", 800)
	local scale_width = screen_width / logosize
	local scale_height = screen_height / logosize

	local bg = gui.get_node("background")
	gui.set_position(bg, vmath.vector3(screen_width/2, screen_height/2, 0))
	gui.set_size(bg, vmath.vector3(screen_width, screen_height, 0))

	local camera = gui.get_node("camera")
	gui.set_position(camera, vmath.vector3(screen_width/2, screen_height/2, 0))
	gui.set_size(camera, vmath.vector3(screen_width/2, screen_height/2, 0))

	local qrcode = gui.get_node("qrcode")
	gui.set_position(qrcode, vmath.vector3(screen_width/2, screen_height/2, 0))
	gui.set_size(qrcode, vmath.vector3(screen_width/2, screen_height/2, 0))

	local n = gui.get_node("scan_bn/larrylabel")
	self.scan_label_pos = gui.get_position(n)
	
	n = gui.get_node("generate_bn/larrylabel")
	self.generate_label_pos = gui.get_position(n)
end

function final(self)
	-- Add finalization code here
	-- Remove this function if not needed
end

function update(self, dt)
	-- Add update code here
	-- Remove this function if not needed
end

local function set_text(self, text)
	local n = gui.get_node("text")
	gui.set_text(n, text)
end

function on_message(self, message_id, message, sender)
	if message_id == hash("set_text") then
		set_text(self, message.text)
	end
end

local function isempty(s)
	return s == nil or s == ''
end

function on_input(self, action_id, action)
	dirtylarry:button("scan_bn", action_id, action, function ()
		msg.post("controller", "click", {mode="SCAN"})
	end)
	dirtylarry:button("generate_bn", action_id, action, function ()
		local text = sys.get_sys_info().device_ident
		if isempty(text) then
			text = "DEFOLD RULES!"
		end
		set_text(self, text)
		msg.post("controller", "click", {mode="GENERATE", text=text})
	end)

	-- for some reason, the text recenters, and I don't want that
	local n = gui.get_node("scan_bn/larrylabel")
	gui.set_position(n, self.scan_label_pos)

	n = gui.get_node("generate_bn/larrylabel")
	gui.set_position(n, self.generate_label_pos)
end

