--[[  v1.0
2025-01-19 Scripted by Koentje

                                            _________________ vertical position in pixels
                                           |  _______________ horizontal position in pixels
                                           | |  _____________ width of image
                                           | | |    _________ height of image
                                           | | |   |    _____ Show image at frame nr
                                           | | |   |   |    _ Hide image at frame nr
                                           | | |   |   |   |
usage:  ${lua conky_image /path/to/picture 2 2 380 425 100 110}

]]

require 'cairo'
require "imlib2"


function frameDrawImage(frcr,path,xx,yy,ww,hh,tt)
    local img =  cairo_image_surface_create_from_png(path)
    local w_img = cairo_image_surface_get_width(img)
    local h_img = cairo_image_surface_get_height(img)

    local tt = tonumber(tt)
    if tt == nil then tt = 100 end
    if tt <= 100 then
      if tt >= 0 then
        alph = (tt / 100)
      else
        alph = 1
      end
    else
     alph = 1
    end

    cairo_save(frcr)
    cairo_translate (frcr, xx, yy)
    cairo_scale (frcr, ww/w_img, hh/h_img)
    cairo_set_source_surface (frcr, img, xx + 6, yy + 3)
    cairo_paint_with_alpha (frcr, alph)
    cairo_surface_destroy (img)
    collectgarbage ()
    cairo_restore (frcr)
end



function conky_atframe(img,xxx,yyy,www,hhh,frstart,frstop)
  if conky_window==nil then return '' end
  local frcs=cairo_xlib_surface_create(conky_window.display,conky_window.drawable,conky_window.visual, conky_window.width,conky_window.height)
  local frcr=cairo_create(frcs)
  local updates=conky_parse('${updates}')
  update_num=tonumber(updates)

   if frstart == nil then
     print("\27[31mERROR:\27[m No start frame nr for '".. img .."'")
     os.exit()
   end
   if frstop == nil then
     print("\27[31mERROR:\27[m No stop frame nr for '".. img .."'")
     os.exit()
   end
   framestart = tonumber(frstart)
   framestop  = tonumber(frstop)


   -- Get frame number from sconky_slideshow_index
   indexfile="./images/space/current/conky_slideshow_index"
   if io.open(indexfile, "r") == nil then
      print("ERROR: Could not find '".. indexfile .."' !") os.exit()
   else
      frcmd="echo $(cat \"".. indexfile .."\")"
      local frhandle = io.popen(frcmd)
      local output = frhandle:read("*a")
      local frresult = output:gsub('[\r]', '')
      frhandle:close()
      framenr = tonumber(frresult)
    end

    -- To test
-- print("framenr: "..framenr, "framestart: "..framestart, "  framestop: "..framestop, "img: "..img)
   if framenr >= framestart and framenr <= framestop then
    frameDrawImage(frcr,img,xxx,yyy,www,hhh, 100)
   end

   cairo_surface_destroy(frcs)
   cairo_destroy(frcr)
  return ''
end
