--@name Custom watermark
--@version 1.0.0
--@author wolfhack docs
--@api 1.0
--@description A small watermark with your own text, the frame rate, the clock and the map. Configure it on its tab on the Scripts page.
-- No permissions needed. Install: Scripts > paste the path of this file > Install, then switch the script on.

local TEXT_SIZE = 14
local PAD_X, PAD_Y = 10, 6
local CORNERS = { "Top left", "Top right", "Bottom left", "Bottom right" }

local fade = 0          -- 0..1, follows the "show" setting so the watermark fades instead of popping

-- The tab. Every control has an id, so its value is saved and read back with store.get(id, default).
ui.tab("Watermark", function()
  ui.card("Content", function()
    ui.toggle("show", "Show the watermark", true)
    ui.input("text", "Text", "wolfhack")
    ui.toggle("show_fps", "Frame rate", true)
    ui.toggle("show_time", "Clock", true)
    ui.toggle("show_map", "Map name", false)
  end, { width = 0.5 })

  ui.card("Look", function()
    ui.dropdown("corner", "Corner", CORNERS, 2)
    ui.slider("margin", "Margin", 0, 80, 16, { int = true, format = "%d px" })
    ui.color("accent", "Accent line", 0x750851FF)
    ui.slider("opacity", "Background opacity", 0, 1, 0.85)
  end, { width = 0.5 })
end)

-- Builds the line of text from the settings.
local function build_text()
  local parts = { store.get("text", "wolfhack") }
  if store.get("show_fps", true) then
    parts[#parts + 1] = string.format("%d fps", math.floor(app.fps() + 0.5))
  end
  if store.get("show_time", true) then
    parts[#parts + 1] = os.date("%H:%M", time.wall())
  end
  if store.get("show_map", false) then
    local snap = data.snapshot()
    if snap.in_game and snap.map ~= "" then parts[#parts + 1] = snap.map end
  end
  return table.concat(parts, "  |  ")
end

events.on("draw", function()
  fade = anim.approach(fade, store.get("show", true) and 1 or 0, 14, time.dt())
  if fade < 0.01 then return end

  local text = build_text()
  local w, h = draw.text_size(text, { size = TEXT_SIZE })
  local box_w, box_h = w + PAD_X * 2, h + PAD_Y * 2

  local sw, sh = app.screen_size()
  local margin = store.get("margin", 16)
  local corner = store.get("corner", 2)                      -- 1 top left, 2 top right, 3 bottom left, 4 bottom right
  local x = (corner == 2 or corner == 4) and (sw - box_w - margin) or margin
  local y = (corner == 3 or corner == 4) and (sh - box_h - margin) or margin

  draw.alpha(fade)
  draw.rect(x, y, box_w, box_h, color.alpha(0x101418FF, store.get("opacity", 0.85)), 4)
  draw.rect(x, y + 3, 2, box_h - 6, store.get("accent", 0x750851FF))
  draw.text(x + PAD_X, y + PAD_Y, 0xF0F0F0FF, text, { size = TEXT_SIZE })
  draw.alpha(1)
end)
