class 'Camera' (Appliance)

Camera.minX = 230
Camera.maxX = 550
Camera.minTopY = -110
Camera.maxTopY = -144

Camera.speed = 0
Camera.destX = 0
Camera.maxSpeed = 300
Camera.accDec = 150
Camera.accInc = 350

Camera.topSprite = nil

function Camera:__init() super()
	self.topSprite = createSprite()
	
	self.topSprite.speed = 0
	self.topSprite.destX = 0
	self.topSprite.maxSpeed = 300
	self.topSprite.accDec = 150
	self.topSprite.accInc = 350
	
	
	self.topSprite:setDefaultSection(player:getCurrentResourceSection())
	self.topSprite:setX(-40)
	self.topSprite:setY(self.maxTopY)
	self.topSprite:animate("DECO_CAMERA_TOP", 0)
	self:addChild(self.topSprite)
end

function Camera:CalculateNewSpeedAndPosition(time, currentPos, targetPos, curSpeed, maxSpeed, accelecrationInc, accelecrationDec)
	local breakDistance = curSpeed * curSpeed / (2 * accelecrationDec)
	local delta = targetPos - currentPos

	if (math.abs(delta) < breakDistance) then
		local acc = (accelecrationDec * time) / 1000
		if (curSpeed > 0) then
			curSpeed = curSpeed - acc
			if (curSpeed < 0) then
				curSpeed = 0
			end
		else
			curSpeed = curSpeed + acc
			if (curSpeed > 0) then
				curSpeed = 0
			end
		end
	else
		local acc = (accelecrationInc * time) / 1000
		if (delta > 0) then
			curSpeed = curSpeed + acc
			if (curSpeed > maxSpeed) then
				curSpeed = maxSpeed
			end
		else
			curSpeed = curSpeed - acc
			if (curSpeed < -maxSpeed) then
				curSpeed = -maxSpeed
			end
		end
	end

	local onLeftSide = (currentPos < targetPos)
	currentPos = currentPos + ((curSpeed * time) / 1000)
	if (currentPos < targetPos ~= onLeftSide) then
		currentPos = targetPos
		curSpeed = 0
	end
	
	return currentPos, curSpeed
end

function Camera:onTick(time)

    if (not dayEnded) then
		if (emily:getY() < self:getY()) then
			return
		end
		
		local pos = 0
		local target = math.max( self.minX, math.min( self.maxX, emily:getX() ) )
		pos, self.speed = self:CalculateNewSpeedAndPosition(time, self:getX(), target, self.speed, self.maxSpeed, self.accInc, self.accDec)
		self:setX(pos)
	
		target = (emily:getY() / 600) * (self.maxTopY - self.minTopY) + self.minTopY
		pos, self.topSprite.speed = self:CalculateNewSpeedAndPosition(time, self.topSprite:getY(), target, self.topSprite.speed, self.topSprite.maxSpeed, self.topSprite.accInc, self.topSprite.accDec)
		self.topSprite:setY(pos)
	end

end

function Camera:onCreate()
	Appliance.onCreate(self)	
end
