------------------------------------------------------------------------------
-- Imports
------------------------------------------------------------------------------

local love       = require 'love'
local make_class = require 'src.utils.classes'


------------------------------------------------------------------------------
-- Class definitions
------------------------------------------------------------------------------

local Fader = make_class()


------------------------------------------------------------------------------
-- Class methods
------------------------------------------------------------------------------

function Fader:_init()
    self.t        = 0.0
    self.step     = 0
    self.done     = true
    self.reverse  = false
    self.callback = nil
end


function Fader:_reset()
    self.t    = 0
    self.step = 0
    self.done = false
end


function Fader:fade_in(callback)
    self:_reset()
    self.reverse  = true
    self.callback = callback
end


function Fader:fade_out(callback)
    self:_reset()
    self.reverse  = false
    self.callback = callback
end


function Fader:update(dt)
    -- While the fader is active.
    if not self.done then
        -- Update the internal timer.
        self.t = self.t + dt

        -- Advance the fade if enough time has passed.
        if self.t >= 0.009 then
            self.step = self.step + 1
            self.t    = 0.0
        end

        -- Mark as done when all fade tiles have been shown/hidden.
        if self.step > 175 then
            self.done = true

            -- Execute the callback if any.
            if self.callback ~= nil then
                self.callback()
                self.callback = nil
            end
        end
    end
end


function Fader:draw()
    local c = 1

    -- Set the render color to black.
    love.graphics.setColor(0, 0, 0)

    -- For every fader tile.
    for i = 0, 16 do
        for j = 0, 10 do
            -- Check if this is a fade in or fade out.
            if not self.reverse then
                -- If it's a fade out then draw black tiles until c.
                if c <= self.step then
                    love.graphics.rectangle('fill', 20 * i, 20 * j, 20, 20)
                end
            else
                -- If it's a fade in then draw black tiles with indices higher than c.
                if c > self.step then
                    love.graphics.rectangle('fill', 20 * i, 20 * j, 20, 20)
                end
            end

            -- Advance to the next tile to show/hide.
            c = c + 1
        end
    end

    -- Reset the render color to white.
    love.graphics.setColor()
end


------------------------------------------------------------------------------
-- Module return
------------------------------------------------------------------------------

return Fader
