local math = math

View = class("View")

function View:updateSize()
	self.width = self.current:get_width()
	self.height = self.current:get_height()
	self.left = self.current.l
	self.right = self.current.r
	self.top = self.current.t
	self.bottom = self.current.b
end

function View:new(left, top, right, bottom)
	local v = instance(self)
	v.visible = true
	v.current = Bounds:new(left or 0, top or 0, right or (window.w-1), bottom or (window.h-1))
	v.clip = Bounds:copy(v.current)
	v.scissor = true
	v:updateSize()
	return v
end

function View:setBounds(left, right, top, bottom)
	self.current:set(left, right, top, bottom)
	self:updateSize()
end

function View:getCenterX()
	return self.current:getCenterX()
end

function View:getCenterY()
	return self.current:getCenterY()
end

function View:x_to_screen(x)
	return x + self.left
end

function View:y_to_screen(y)
	return y + self.top
end

function View:screen_x_to_view(x)
	return x - self.left
end

function View:screen_y_to_view(y)
	return y - self.top
end

function View:setVisible(val)
	self.visible = val
end

function View:isVisible()
	return self.visible
end

function View:clampPosition(x,y,xpadding,ypadding)
	local xpadding = xpadding or 0
	local ypadding = ypadding or 0
	return math.min(self.current.r - math.min(xpadding,self.width/2), math.max(self.current.l + math.min(self.width/2,xpadding), x)), math.min(self.current.b - math.min(ypadding,self.height/2), math.max(self.current.t + math.min(self.height/2,ypadding), y))
end

function View:disableScissor()
	self.scissor = false
end

function View:setScissorClip(left, top, right, bottom)
	self.clip:set(left or self.target.l, top or self.target.t , right or self.target.r, bottom or self.target.b)
end

function View:applyInsideScissorClip(left, top, right, bottom)
	video.setScissorClip(math.max(self.clip.l, left), math.max(self.clip.t, top), math.min(right, self.clip.r), math.min(bottom,self.clip.b))	
end

function View:applyScissorClip()
	video.setScissorClip(self.clip.l, self.clip.t, self.clip.r, self.clip.b)	
end

function View:restoreScissorClip()
	video.clearScissorClip()
end

function View:apply()
	if self.scissor then
		self:applyScissorClip()
	end
end

function View:restore()
	if self.scissor then
		self:restoreScissorClip()
	end
end

function View:render()
	video.renderSpriteRectangleOutline(self.left, self.top, self.right, self.bottom, 255, 255, 0, 0, nil,nil, 5)
	video.renderTextSprites(self.width, (self.left+self.right)*0.5, self.top + 20, 1, "small", 255,255,0,0)
	video.renderTextSprites(self.height, self.left+20, (self.top + self.bottom)*0.5 , 0, "small", 255,255,0,0)
end