-- created by Bertrand Legruley
-- lestrucsetastucesdetux@free.fr
-- lestrucsetastucesdetux.pages-perso.free.fr

local assdraw = require 'mp.assdraw'
local mp = require 'mp'

local base_text_playing = "Audio playing now"
local blink_state = 0
local color = "&HE8731A&"
local direction = 1
local dot_count = 0
local max_dots = 3
local paused = false
local showing = false
local timer = nil

local function show_text()
    if not showing then return end

    local ass = assdraw.ass_new()
    local w, h = mp.get_osd_size()
    local fs = math.max(20, math.floor(h * 0.05))
    local next_duration

    if paused then
        if blink_state == 0 then
            ass:append(string.format("{\\an5\\fs%d\\fnLiberation Sans\\1c%s\\i1\\alpha&H00&}█ █{\\i0}", fs, color))
            blink_state = 1
            next_duration = 1.0
        else
            ass:append(string.format("{\\an5\\fs%d\\fnLiberation Sans\\1c%s\\i1\\alpha&HFF&}█ █{\\i0}", fs, color))
            blink_state = 0
            next_duration = 0.5
        end
    else
        local dots = string.rep(".", dot_count)
        ass:append(string.format("{\\an5\\fs%d\\fnLiberation Sans\\1c%s\\i1}%s%s{\\i0}", fs, color, base_text_playing, dots))

        dot_count = dot_count + direction
        if dot_count >= max_dots then
            direction = -1
            dot_count = max_dots
        elseif dot_count <= 0 then
            direction = 1
            dot_count = 0
        end

        blink_state = 0
        next_duration = 1.0
    end

    mp.set_osd_ass(w, h, ass.text)

    if timer then timer:kill() end
    timer = mp.add_timeout(next_duration, show_text)
end

local function start_display()
    if timer then timer:kill() end

    blink_state = 0
    direction = 1
    dot_count = 0
    showing = true

    show_text()
end

local function stop_display()
    showing = false

    if timer then timer:kill() end
    timer = nil

    mp.set_osd_ass(0, 0, "")
end

mp.observe_property("pause", "bool", function(_, value)
    if showing then
        blink_state = 0
        direction = 1
        dot_count = 0
        paused = value
        show_text()
    end
end)

mp.register_event("file-loaded", function()
    local aid = mp.get_property_number("aid", 0)
    local vid = mp.get_property_number("vid", 0)

    if aid > 0 and vid == 0 then
        paused = mp.get_property_native("pause", false)
        start_display()
    else
        stop_display()
    end
end)

mp.register_event("end-file", stop_display)
