--!name Daily Quote
--!icon quote
--!category Tools
-- A quote each time you open it (or press OK). Fetches one from ZenQuotes
-- over Wi-Fi; without a connection it picks from the ones built in below.

local OFFLINE = {
  {"Well begun is half done.", "Aristotle"},
  {"The journey of a thousand miles begins with one step.", "Lao Tzu"},
  {"It does not matter how slowly you go as long as you do not stop.", "Confucius"},
  {"We are what we repeatedly do.", "Will Durant"},
  {"Nothing is particularly hard if you divide it into small jobs.", "Henry Ford"},
  {"Waste no more time arguing what a good man should be. Be one.", "Marcus Aurelius"},
  {"The best time to plant a tree was 20 years ago. The second best time is now.", "Proverb"},
  {"Simplicity is the ultimate sophistication.", "Leonardo da Vinci"},
  {"I have never let my schooling interfere with my education.", "Mark Twain"},
  {"A reader lives a thousand lives before he dies.", "George R. R. Martin"},
}

local text, author, source

-- ZenQuotes answers [{"q":"quote","a":"author",...}]. JSON escapes are
-- undone for quotes and backslashes; anything fancier is rare in a quote.
local function fetch()
  local body = snail.fetch("https://zenquotes.io/api/random")
  if not body or #body == 0 then return false end
  local q = body:match('"q"%s*:%s*"(.-)"%s*,')
  local a = body:match('"a"%s*:%s*"(.-)"%s*,')
  if not q or q == "" then return false end
  local function unescape(s) return (s:gsub('\\"', '"'):gsub("\\/", "/"):gsub("\\\\", "\\")) end
  text, author = unescape(q), a and unescape(a) or ""
  return true
end

local function next_quote()
  if fetch() then
    source = "from zenquotes.io"
    return
  end
  -- Offline: step through the built-in list, remembering where we got to.
  local n = tonumber(snail.load()) or 0
  local pick = OFFLINE[(n % #OFFLINE) + 1]
  snail.save(tostring(n + 1))
  text, author = pick[1], pick[2]
  source = "offline"
end

function start()
  snail.tick(0)
  next_quote()
end

function key(k)
  if k == "ok" then next_quote() end
end

function draw()
  snail.title("Daily Quote")
  snail.gap()
  snail.center(true)
  snail.text('"' .. (text or "") .. '"')
  if author and author ~= "" then
    snail.gap()
    snail.small("- " .. author)
  end
  snail.center(false)
  snail.status(source or "")
  snail.hint("OK another")
end
