#!/usr/bin/env bash

if [ ! -p "$UFIFO" ];then
    printf 'UFIFO not set\n'
    exit
fi

# echo $ID
source $(ueberzug library)
function set_image {
    x_size=$(tput cols)
    y_size=$(tput lines)
    MAX_COLUMNS=$(($x_size * 3 / 10 ))
    # MAX_COLUMNS=100
    x=$(($x_size-$MAX_COLUMNS-5))
    y=$(($y_size/2))
    ImageLayer::add [identifier]="$ID" [x]="${x}" [y]="${y}" \
                    [max_width]="${MAX_COLUMNS}" \
                    [path]="$@" \
                    >"$UFIFO"
}
function remove_image {
    ImageLayer::remove [identifier]="$ID" \
                    >"$UFIFO"
}

IMG_URL=$(cat $@ | grep image | awk 'NR==2 {print $2}')
LINK=$(cat $@ | grep ^Link: | head -1 | cut -d: -f2-)
# echo $LINK
# non posix
# if [[ "$LINK" =~ "https://www.youtube.com/.*" ]];then

(
if [[ "$LINK" =~ "www.youtube.com" ]];then
    # extract video id.
    VIDEO_ID=$(echo $LINK | cut -d= -f2)
    IMG_URL="https://img.youtube.com/vi/$VIDEO_ID/hqdefault.jpg"
    # youtube-dl --write-thumbnail --skip-download $LINK --output /tmp/temp &> /dev/null
fi
if [ -n "$IMG_URL" ];then
    curl -o /tmp/temp $IMG_URL &>/dev/null
fi

if [ -f "/tmp/temp" ];then
    set_image /tmp/temp
fi
) &

nvim -R -c 'set ft=mail nomod noma nolist' -c 'nnoremap q :qa! <CR>' $@
remove_image
if [ -f /tmp/temp ];then
    rm /tmp/temp
fi
