-- animated_clock.lua – Image-based Clock with Flip Animation (Hours, Minutes)
-- Corrected to persist animation state across frames
--
-- 2025-nov-10: Modification by Koentje  (remon@cobrasoft.nl)

require 'cairo'
local status, cairo_xlib = pcall(require, 'cairo_xlib')
if not status then
    cairo_xlib = setmetatable({}, { __index = _G })
end

-- This scipts filename
local SCRIPT_NAME = string.gsub(string.match(debug.getinfo(1, 'S').short_src, "[^/]+$"), '.lua', '')

--  Read settings.ini file
path = ("./settings.ii")
   if io.open(path, "r") == nil then
      print(SCRIPT_NAME .. ".lua: \27[31mNo settings.ini found !\27[m")
      os.execute("pkill -f forecast.conky")
   else
      file = io.open(path)
      lines = file:lines()
      for line in lines
      do
        local key = {line}
        mykey = string.sub(key[1],1,7)
          if mykey == "ctheme=" then
            ctheme = string.sub(key[1], 9, -2)
            print("Theme: " .. ctheme)
          end
        mykey = string.sub(key[1],1,7)
          if mykey == "ttppos=" then
            ttppos = string.sub(key[1], 9, -2)
          end
        mykey = string.sub(key[1],1,8)
          if mykey == "csmooth=" then
            csmooth = string.sub(key[1], 10, -2)
            value = tonumber(csmooth)
            if value >= 1 and value <= 10 then
              csmooth = value
            else
              print(SCRIPT_NAME .. ".lua: \27[31m'csmooth=" .. csmooth .. "' is out of boundary! Must be between 1-10. See settings.ini\27[m")
              os.execute("pkill -f forecast.conky")
              return
            end
          end
      end
   end

-- Global animation state
local previous_minute = -1
local animation_frame = 0
local animation_duration = csmooth
local is_animating = false
local previous_digits = {0, 0, 0, 0}
local current_digits = {0, 0, 0, 0}

-- Load digit surfaces once
local digits = {}
for i = 0, 9 do
    digits[i] = cairo_image_surface_create_from_png("clockimages/" .. ctheme .. "/" .. i .. ".png")
end
local image_bg = cairo_image_surface_create_from_png("clockimages/" .. ctheme .. "/BG.png")

-- Helper to draw a digit
local function draw_digit(cr, digit, x, y, y_offset, alpha)
    local img = digits[digit]
    local w = cairo_image_surface_get_width(img)
    local h = cairo_image_surface_get_height(img)

    cairo_save(cr)
    cairo_translate(cr, x, y + y_offset)
    cairo_scale(cr, 40 / w, 72 / h)
    cairo_set_source_surface(cr, img, 82, 0)
    cairo_paint_with_alpha(cr, alpha)
    cairo_restore(cr)
end

function conky_clock()
    if conky_window == nil then return end

    local cs = cairo_xlib_surface_create(conky_window.display, conky_window.drawable, conky_window.visual,
                                         conky_window.width, conky_window.height)
    local cr = cairo_create(cs)

    -- Current time digits
    local hours = os.date("%H")
    local mins = os.date("%M")
    local now_minute = tonumber(mins)

    local new_digits = {
        tonumber(hours:sub(1, 1)),
        tonumber(hours:sub(2, 2)),
        tonumber(mins:sub(1, 1)),
        tonumber(mins:sub(2, 2))
    }

    -- Detect minute change
    if now_minute ~= previous_minute then
        previous_minute = now_minute
        previous_digits = current_digits
        current_digits = new_digits
        animation_frame = 0
        is_animating = true
    end

    -- Draw background
    local w = cairo_image_surface_get_width(image_bg)
    local h = cairo_image_surface_get_height(image_bg)
    cairo_translate(cr, -21, -20)
    cairo_save(cr)
    cairo_scale(cr, 306 / w, 166 / h)
    cairo_set_source_surface(cr, image_bg, 80, 8)
    cairo_paint(cr)
    cairo_restore(cr)

    -- Digit positions and drawing
    local x_positions = {50, 95, 170, 215}
    local y_base = 48

if is_animating then
    animation_frame = animation_frame + 1
    local linear = math.min(animation_frame / animation_duration, 1)
    local progress = linear * linear * (3 - 2 * linear)  -- Smoothstep easing

    if linear >= 1 then
        is_animating = false
    end


        for i = 1, 4 do
            if previous_digits[i] ~= current_digits[i] then
                -- Animate only changing digits
                draw_digit(cr, previous_digits[i], x_positions[i], y_base, progress * 60, 1 - progress)
                draw_digit(cr, current_digits[i], x_positions[i], y_base, -60 * (1 - progress), progress)
            else
                -- Static digit
                draw_digit(cr, current_digits[i], x_positions[i], y_base, 0, 1)
            end
        end
    else
        -- Static full display
        for i = 1, 4 do
            draw_digit(cr, current_digits[i], x_positions[i], y_base, 0, 1)
        end
    end

    conky_parse("${lua conky_image ./weatherimages/weather-1.png " .. ttppos .." 260 160}")
    cairo_destroy(cr)
    cairo_surface_destroy(cs)

end

