local CharManager = Object:extend()
local Dummy   = Object:extend()
local Player  = Dummy:extend()
local Rival   = Dummy:extend()
local actor   = require "scenes.subgame.sonic-boost.actors"


function CharManager:new(controller)
  self.controller = controller
  self.list = {}
end

function CharManager:newPlayer(character, rail)
  local id = #self.list + 1
  table.insert(self.list, Player(self, id, character, rail))
end

function CharManager:newDummy(character, rail)
  local id = #self.list + 1
  table.insert(self.list, Dummy(self, id, character, rail))
end

function CharManager:update(dt)
  for i,v in ipairs(self.list) do
    v:update(dt)
  end
end

function CharManager:getType(id)
  self.list[id]:getType()
end

-- DUMMY CHARACTER FUNCTION --

function Dummy:new(manager, playerid, character, rail)
  self.manager    = manager
  self.controller = manager.controller
  self.type       = "dummy"

  local character = character or "sonic"

  local rail = rail

  local spritepath = "assets/sprites/characters/subgame/sonic-boost/" .. character
  self.controller.assets:addSprite("character" .. playerid, spritepath)

  self.actor = actor.Character(self, rail, character, playerid)
end


function Dummy:getKeys()
  return core.input.fakekeys
end

function Dummy:update(dt)
  -- le Dummy ne fait rien, donc inutile
end

function Dummy:newLap()
  local currentTurn, maxTurn = self.actor.turn, self.controller.missiondata.turns

  if (currentTurn < maxTurn) then
    self:wrapActor()
  else
    self:finishLevel()
  end
end

function Dummy:wrapActor()
  self.actor.x = math.floor(self.actor.x - self.controller.world.width)
  self.actor.turn = self.actor.turn + 1
end

function Dummy:getRealPosition()
  local turn = self.actor.turn - 1 -- on calcule le tour à partir de 0 pour
  -- obtenir le vrai x. Techniquement, ça ne change rien pour le joueur,
  -- mais c'est plus correct comme ça

  local turnStart = (turn * self.controller.world.width)

  return turnStart + self.actor.x
end

function Dummy:finishLevel()
  -- Pour le Dummy ça n'a aucun effet
end

function Dummy:die()
  self.actor:destroy()
end

-- PLAYER CONTROL FUNCTION --

function Player:new(manager, playerid, character, rail)
  Player.super.new(self, manager, playerid, character, rail)

  self.type = "player"
  self.controller.camera:setTarget(self.actor)
  self.controller.hud:setTarget(self.actor)
end

function Player:getKeys()
  return self.controller.keys
end

function Player:wrapActor()
  self.actor.view.x = math.floor(self.actor.view.x - self.controller.world.width)
  self.actor.turn = self.actor.turn + 1
  self.controller.camera.view.x = self.controller.camera.view.x - self.controller.world.width
end

function Player:finishLevel()
  --love.event.quit()
end

function Player:die()
  love.event.quit()
end

return CharManager
