#!/usr/bin/env fish

set -l cache_base $HOME/.cache
set -q XDG_CACHE_HOME; and set cache_base $XDG_CACHE_HOME
set -l thumb_dir "$cache_base/cliphist/thumbnails"

set -l list (cliphist list)
if test -z "$list"
    notify-send cliphist "clipboard empty"
    exit
end

mkdir -p $thumb_dir

for line in $list
    string match -rq '^(?<id>\d+)\t\[\[ binary data \S+ \S+ (?<ext>jpg|jpeg|png|bmp|gif|webp)\b' -- $line; or continue
    set -l thumb "$thumb_dir/$id.$ext"
    test -f $thumb; and continue
    echo $line | cliphist decode >$thumb 2>/dev/null
end

for f in $thumb_dir/*
    test -f $f; or continue
    set -l fid (basename $f | string replace -r '\.[^.]+$' '')
    string match -rq "^$fid\t" -- $list; or rm -f $f
end

set -l item (swayimg -g --appid=swayimg-picker $thumb_dir -c ~/.config/swayimg/picker.lua -e 'swayimg.gallery.set_aspect("fit")')
if test -n "$item"
    set -l mime (file --mime-type -b $item)
    wl-copy --type $mime <$item
end
