dofile ( "Scripts/clickable.lua" )

--
-- Button
--

Button = {}
ButtonMT = { __index = Button }

-- inherit Clickable
setmetatable ( Button, { __index = Clickable } )

function Button:Create ( x, y, z, width, height, font, text )

	local button = {}
	setmetatable ( button, ButtonMT )

	button.x = x
	button.y = y
	button.z = z
	button.width = width
	button.height = height
	button.font = font
	button.text = text

	button.sprite = Sprite ( x, y )
	button.sprite.depth = z
	display:add_child ( button.sprite )

	button.down = false

	button:Paint ( )

	return button

end

function Button:Destroy ( )

	display:remove_child ( self.sprite )

end

function Button:SetPosition ( x, y )
	self.sprite:set_position ( x, y )
	self.x = x
	self.y = y
end

function Button:Paint ( )

	self.sprite.canvas:clear ( )

	local bottom, top
	if self.down == true then
		bottom = DARKRED
		top = RED
	else
		bottom = RED
		top = DARKRED
	end
	self.sprite.canvas:move_to ( 0, 0 )
	self.sprite.canvas:line_to ( self.width, 0 )
	self.sprite.canvas:line_to ( self.width, self.height )
	self.sprite.canvas:set_line_style ( 1, top, 1 )
	self.sprite.canvas:stroke ( )
	self.sprite.canvas:move_to ( 0, 0 )
	self.sprite.canvas:line_to ( 0, self.height )
	self.sprite.canvas:line_to ( self.width, self.height )
	self.sprite.canvas:set_line_style ( 1, bottom, 1 )
	self.sprite.canvas:stroke ( )

	self.sprite.canvas:set_font ( self.font )
	local text = self.text
	local x = self.width / 2 - self.font:get_width ( text ) / 2
	local y = self.height / 2 - self.font:get_size ( ) / 2
	if self.down == true then
		y = y - 1
	end
	self.sprite.canvas:move_to ( x, y )
	self.sprite.canvas:write ( text )

end


function Button:MouseRelease ( button, x, y )
	self.down = false
	self:Paint ( )
	self:OnPress ( button, x, y )
end

function Button:MousePress ( button, x, y )
	self.down = true
	self:Paint ( )
	self:OnRelease ( button, x, y )
end
