class = require 'engine/libs/30log'
Global = require 'engine/global'

local Gridwalker = require 'engine/controllers/gridwalker'
local Level = require 'engine/level'
local sound = require 'engine/sound'
local story = require 'story'

Engine = class('Engine')

Engine.inputMap = {}
Engine.inputMap['w'] = 'up'
Engine.inputMap['s'] = 'down'
Engine.inputMap['a'] = 'left'
Engine.inputMap['d'] = 'right'
Engine.inputMap['up'] = 'up'
Engine.inputMap['down'] = 'down'
Engine.inputMap['left'] = 'left'
Engine.inputMap['right'] = 'right'
Engine.inputMap['k'] = 'up'
Engine.inputMap['j'] = 'down'
Engine.inputMap['h'] = 'left'
Engine.inputMap['l'] = 'right'
Engine.inputMap['return'] = 'enter'

Engine.controllers = {gridwalker = Gridwalker}

function Engine:init()
    story:start(self)
end

function Engine:load(level)
    self.level = Level(level)
end

function Engine:update(dt)
    self.level:update(dt)
    love.audio.update()

    local input = Engine:getInput()
    if input ~= nil then
        self.level:checkObjectKeys(dt, input)
    end
end

function Engine:draw(dt)
    self.level:draw()
end

function Engine:checkObjectAnimation(key)
    local input = Engine.inputMap[key]
    if input ~= nil then
        self.level:checkObjectAnimation(input)
    end
end

function Engine:showMessage(message)
    self.level:showMessage(message)
end

function Engine:animate(objectName, animationName)
    self.level:startAnimate(objectName, animationName)
end

function Engine:stopAnimate(objectName)
    self.level:stopAnimate(objectName)
end

function Engine:playSound(soundName, loop, finishedFunc)
  return love.audio.play('assets/sound/' .. soundName .. '.ogg', 'stream', loop, finishedFunc)
end

function Engine:getInput()
    local foundInput = nil

    for key, input in pairs(Engine.inputMap) do
        if love.keyboard.isDown(key) then
            foundInput = input
            break
        end
    end

    return foundInput
end

return Engine
