local module = {}

-- local myTypes = require("modules.types")
local files = require("modules.files")
local json = require("modules.json")

local CharacterClass = {}
CharacterClass.__index = CharacterClass

function CharacterClass:PlayAnimation(name)
    local animName = self.animations[name]
    self.sprite:PlayAnimation(animName, self.animInfo[name].fps)
    self.sprite.extraOffset = module.myTypes.Vector2(self.animInfo[name].offsets[1] - self.stagePosition.x, self.animInfo[name].offsets[2] - self.stagePosition.y)
    self.singing = name ~= "idle"
end

function module.character(name)
    local charFile = files.read_file(string.format("characters/%s.json", name))
    if not charFile then
        error("Failed to load character "..name)
    end

    local parsed = json.parse(charFile)

    local image = parsed.image..".png"
    local sheet = parsed.image..".json"

    local sprite = module.myTypes.Sprite(image, sheet)
    sprite.position = module.myTypes.Vector2(parsed.position[1], parsed.position[2])

    local newCharacter = setmetatable({
        scale = parsed.scale,
        animations = {},
        animInfo = {},
        sprite = sprite,
        singing = false,
        stagePosition = module.myTypes.Vector2(0,0) -- Changeable
    }, CharacterClass)

    for index, alias in next, parsed.animations do
        newCharacter.animations[alias.anim] = alias.name
        newCharacter.animInfo[alias.anim] = alias
    end

    newCharacter:PlayAnimation("idle")

    return newCharacter
end

return module