local node = Node:extend('nodes.slideshow', {})

local smallFont = love.graphics.newFont('fonts/Lato-Light.ttf', 50)

function node:init(config)
  node.super.init(self, config)
  self:loadImage()
end

function node:loadImage()
  if self.files then
    local files = self:processFiles(self.files)
    if files ~= nil then
      if self.fileName then
        self.fileName = files[(lume.find(files, self.fileName) or 1) % #files + 1]
      else
        self.fileName = files[1]
      end
    end
  end

  if self.fileName ~= nil and love.filesystem.exists( self.fileName ) then
    self.image = love.graphics.newImage( self.fileName )
  else
    self.image = nil
  end
end

function node:processFiles(files)
  local nFiles = {}

  for _, f in ipairs(files) do
    if love.filesystem.isDirectory(f) then
      print(f, "is directory")
      for _, nf in ipairs(love.filesystem.getDirectoryItems(f)) do
        print(nf, "hey")
        if love.filesystem.isFile(f .. "/" .. nf) then
          nFiles[#nFiles + 1] = f .. "/" .. nf
        end
      end
    else
      print(f, "is file")
      nFiles[#nFiles + 1] = f
    end
  end
  print("expanded to: ", inspect(nFiles))
  return nFiles
end

function node:beforeEnter()
  self:loadImage()
end

function node:render()
  love.graphics.setColor( 0, 0, 0 )
  love.graphics.rectangle("fill", 0, 0, love.graphics.getWidth(), love.graphics.getHeight())
  if self.image == nil then
    love.graphics.setFont(smallFont);
    love.graphics.setColor( 1.0, 1.0, 1.0, 0.5 )
    love.graphics.printf('File not found:\n' .. tostring(self.fileName), 0, love.graphics.getHeight()*0.7 , love.graphics.getWidth(), 'center');
  else
    love.graphics.setColor( 1.0, 1.0, 1.0 )
    love.graphics.draw( self.image, love.graphics.getWidth()/2, love.graphics.getHeight()/2, 0, 1, 1, self.image:getWidth()/2, self.image:getHeight()/2 )
  end

end

return node
