local node = ThreadNode:extend('nodes.weather', {
  threadFile = 'nodes/weather_thread.lua',
  threadChannel = 'weather',

  updateInterval = 5 * 60,
})

local weatherFont = love.graphics.newFont('fonts/weathericons-regular-webfont.ttf', 400)
local textFont = love.graphics.newFont('fonts/Lato-Thin.ttf', 300)
local smallFont = love.graphics.newFont('fonts/Lato-Light.ttf', 30)

local weatherGlyphs = {}

local weatherGlyphsSet = {
  day = {
    snow = "",
    mist = "",
    clear = "",
    -- clouds = "",
    clouds = "", -- x---DDD
    drizzle = "",
  },
  night = {
    snow = "",
    mist = "",
    clear = "",
    clouds = "",
    drizzle = "",
    
  }
}

function node:timeOfDay()
  local sunRise = tonumber(os.date("%H%M", self.state.sunRise)) 
  local sunSet = tonumber(os.date("%H%M", self.state.sunSet))
  local now = tonumber(os.date("%H%M"))
  if sunRise == nil or sunSet == nil then
    return weatherGlyphsSet["day"] -- smth gone wrong. assume daylight
  end
  if now < sunSet and now > sunRise then
     print('day')
     return weatherGlyphsSet["day"]
  else
     print('night')
     return weatherGlyphsSet["night"]
  end
end

function node:beforeEnter()
  if self.state then
    weatherGlyphs = self:timeOfDay()
  else
    weatherGlyphs = weatherGlyphsSet["day"] -- do not know sunraise and sunset yet. assume daylight
  end
end

function node:render()
  love.graphics.setColor( 0, 0, 0 )
  love.graphics.rectangle("fill", 0, 0, love.graphics.getWidth(), love.graphics.getHeight())

  if self.state then
    love.graphics.setColor( 1.0, 1.0, 1.0 )

    if weatherGlyphs[self.state.weather] then
      love.graphics.setFont(weatherFont)
      love.graphics.print(weatherGlyphs[self.state.weather], 120, 35)
    else
      love.graphics.setFont(smallFont)
      love.graphics.print(self.state.weather, 150, love.graphics.getHeight()/2 - 60)
    end

    love.graphics.setFont(textFont)
    love.graphics.printf(tostring(math.floor(self.state.temperature + 0.5)) .. "°", 600, 150, 650, 'center')

    love.graphics.setFont(smallFont)
    love.graphics.printf(os.date("Last update: %Y/%m/%d %H:%M", self.state.lastUpdate), 0, love.graphics.getHeight() - 60, love.graphics.getWidth(), 'center')
    if self.state.insideTemperature then
      love.graphics.printf("Room: " .. tostring(self.state.insideTemperature) .. "° / " .. tostring(self.state.insideHumidity) .. "%RH", 0, love.graphics.getHeight() - 100, love.graphics.getWidth(), 'center')
    end
  else
    love.graphics.setColor( 1.0, 1.0, 1.0, 0.4 )

    love.graphics.setFont(smallFont)
    love.graphics.printf("Loading weather...", 0, love.graphics.getHeight() - 200, love.graphics.getWidth(), 'center')
  end
end

return node
