local love = assert( love )
local scene = require( "scene" )
local settings = require( "scenes.settings" )
local strings = require( "i18n" )
local printString
local fullString
local loadNextScene
local utf8 = require( "utf8" )

local t = {}

local len = 0
local time = 0
local quad

local function noop() end
t.mousemoved = noop
t.mousepressed = noop
t.wheelmoved = noop


function t.keypressed( key, code, isRepeat )
  if code == "escape" then
    love.mouse.setRelativeMode( false )
  end
  if code == "return" then
    if printString ~= fullString then
      printString = fullString
      return
    else
      quad = nil
      return loadNextScene()
    end
  end
end

function t.draw()
  --love.graphics.setScissor( 0, 0, 400, love.graphics.getHeight() )
  love.graphics.setColor( 1, 0.2, 0.2 )
  love.graphics.printf( printString, 10, 10, math.min( 400, love.graphics.getWidth() / 2 ), "left" )
  love.graphics.print( strings.toContinue, 10, love.graphics.getHeight() - love.graphics.getFont():getHeight() )
  love.graphics.setColor( 1, 1, 1 )
  if quad then
    local h = love.graphics.getHeight()
    local s = (love.graphics.getWidth() - 450) / quad:getWidth()
    local y = h - quad:getHeight() * s
    love.graphics.draw( quad, 450, y, 0, s, s)
  end
end

function t.update( dt )
  if printString == fullString then return end
  time = time + dt
  if time > 0.08 then
    time = 0
    len = len + 1
    printString = fullString:sub( 1, ( utf8.offset( fullString, len ) or 0 ) - 1 )
  end
end

function t.play( str, nextScene, img )
  loadNextScene = nextScene
  fullString = str
  printString = ""
  if img then quad = love.graphics.newImage( img ) end
  love.graphics.setScissor()
  love.graphics.clear( )
  return scene.load( t )
end

return t