local vm = require"lib.vornmath"

local main_wrapper = require "love_src.wrapper.lappy.world"
---@class wrappers.Concord.world : lappy.world
local world = main_wrapper:extend()

local reap = require("lib.reap")
local BASE = reap.base_path(...)

local default = {
  racers = {
    base = require "love_src.src.new.components.racer"
  }
}

local entities_default = {
  {
    components = {
      racer = require("love_src.src.new.components.racer"),
      actor = require("love_src.src.new.components.player"),
    },
    type = "racer",
    name = "racer 1",
    data = {
      racer = {
        pos = vm.vec2(44.64, 10.87),

        orientation = vm.vec2(1.0, 0.0),
        orientation_speed = 0.0,
        min_orientation_speed = -1.0,
        max_orientation_speed = 1.0,

        velocity = vm.vec2(0.0, 0.0),
        max_speed = 1.0,
        min_speed = -1.0,
        inertia = vm.vec2(0.0, 0.0),

        accel = 0.1,
        brake = 0.1,
        grip = 0.0,
        steer = 0.1,
        mass = 0.0,
        streamline = 0.0
      },
      actor = {
        forward = 0.0,
        steer = 0.0
      }
    }
  },
  {
    components = {
      map = require"love_src.src.new.components.map"
    },
    type = "map",
    name = "map 1",
    data = {
      map = {
        drag_movement = 0.0,
        friction = 1.0,
        drag =  vm.vec2(1.0, 0.0)
      }
    }
  }
}

function world:new()
  world.super.new(self, BASE, "race")
  self.is_loaded = false
  self.entities = {}
end

function world:load(data, entities_data)
  self.data = data or default
  self.is_loaded = true

  self.entities_data = entities_data or entities_default

  local map
  for _, d in pairs(self.entities_data) do
    local e = {
      type = d.type,
      name = d.name,
      components = {}
    }
    for t, c in pairs(d.components) do
      e.components[t] = c()
      e.components[t]:load(e, d.data[t])
    end
    table.insert(self.entities, e)
    if (e.type == "map") then
      map = e
    end
  end
  for _, e in ipairs(self.entities) do
    if (e.type == "racer") then
      for t, c in pairs(e.components) do
        if (c.name == "racer") then
          c.map = map.components.map
        end
      end
    end
  end

end

function world:update(dt)
  for _, e in ipairs(self.entities) do
    for t, c in pairs(e.components) do
      c:update(dt)
    end
  end
end

function world:draw()
  for _, e in ipairs(self.entities) do
    for t, c in pairs(e.components) do
      c:draw()
    end
  end
end

function world:ui_draw()
  for _, e in ipairs(self.entities) do
    for t, c in pairs(e.components) do
      c:ui_draw()
    end
  end
end

return world
