local Camera = require "libs.hump.camera"
local CameraSystem = Object:extend()

function CameraSystem:new(controller, x, y, target)
  self.controller = controller
  self.target = target
  self.view = Camera(212, 30, 1, 0, true)
  local width, height, flags = love.window.getMode( )
  self.screen = {}
  self.screen.width   = width
  self.screen.height  = height
  self.width  = 424
  self.height = 240
  self.resolution = self.screen.width / self.width
  --self:limit()

  self.turn = 1
end

function CameraSystem:setTarget(target)
  self.target = target
end

function CameraSystem:floorCoord()
  self.view.x, self.view.y = utils.math.floorCoord(self.view.x, self.view.y)
end

function CameraSystem:update()
  if (self.target ~= nil) then
    self:followEntity(self.target)
  end
  self:limit()
  self:floorCoord()
end

function CameraSystem:move(x, y)
  self.view.x = x
  self.view.y = y

  self:limit()
end

function CameraSystem:getCoord()
  local camx, camy, camh, camw
  camx = self.view.x - (self.width/2)
  camy = self.view.y - (self.height/2)

  camw = self.width
  camh = self.height
  return camx, camy, camw, camh
end

function CameraSystem:worldCoord(x, y, ox, oy, w, h)
  ox, oy = ox or 0, oy or 0
	w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight()
  return self.view:worldCoords(x, y, ox, oy, w, h)
end

function CameraSystem:viewCoord(x, y)
  return self.view:cameraCoords(x, y, ox, oy, w, h)
end

function CameraSystem:getScreenCoord()
  local camx, camy, camh, camw
  camx = self.view.x - (self.screen.width/2)
  camy = self.view.y - (self.screen.height/2)

  camw = self.screen.width
  camh = self.screen.height
  return camx, camy, camw, camh
end

function CameraSystem:limit()
  local camx, camy        = self.view.x, self.view.y

  local currentTurn, maxTurn = self.turn, self.controller.missiondata.turns

  if currentTurn == 1 then
    camx = math.max(212, camx)
  end

  if currentTurn == maxTurn then
    camx = math.min(camx, self.controller.world.width - 212 + 31)
  end

  self.view.x, self.view.y = camx, 30
end

function CameraSystem:followEntity(entity)
  local entity = entity

  if (entity ~= nil) then
    self.turn = entity.turn or 1

    local playx, playy = entity:getViewCenter()

    local camx, camy   =  self.view.x + (self.width/2),
                          self.view.y + (self.height/2)


    playx, playy = self:viewCoord(playx-16+212, 30)
    playx = playx - (self.width/2)
    playy = playy - (self.height/2)

    if (math.abs(playx) > 8) then
      camx = camx + (playx - (8*utils.math.sign(playx)))
    end

    if (playy > 16)  then
      camy = camy + (playy - 16)
    elseif (playy < -64) then
      camy = camy + (playy + 64)
    end

    self.view.x, self.view.y =  camx - (self.width/2),
                                camy - (self.height/2)
  end
end

-- Anciennes Fonctions

return CameraSystem
