local wezterm = require 'wezterm'

local themes_dir = wezterm.config_dir .. '/themes'
local state_file = wezterm.config_dir .. '/.current-theme'

local theme_files = {
  'matrix',
  'phosphor-green',
  'phosphor-amber',
  'cyberpunk',
  'nord',
  'tokyonight',
  'dracula',
}

local themes = {}
local order = {}

for _, name in ipairs(theme_files) do
  local ok, theme = pcall(dofile, themes_dir .. '/' .. name .. '.lua')
  if ok and theme and theme.name then
    themes[name] = theme
    order[#order + 1] = name
  else
    wezterm.log_error('wezterm-themes: error loading theme "' .. name .. '": ' .. tostring(theme))
  end
end

local M = {}

function M.names()
  return order
end

function M.get(name)
  return themes[name] or themes[order[1]]
end

function M.current()
  local f = io.open(state_file, 'r')
  local name = f and f:read('*l')
  if f then
    f:close()
  end
  if name and themes[name] then
    return themes[name]
  end
  return themes[order[1]]
end

function M.next(name)
  local cur = name or M.current().name
  local idx = 0
  for i, n in ipairs(order) do
    if n == cur then
      idx = i
      break
    end
  end
  return themes[order[(idx % #order) + 1]]
end

function M.save(theme)
  local f = io.open(state_file, 'w')
  if f then
    f:write(theme.name .. '\n')
    f:close()
  end
end

return M