#!/bin/bash

# Version 2
# Last change:     Mo 2026-06-15
# Git repo:        https://git.fennek.xyz/fennek182/dotfiles
# Latest version:  https://git.fennek.xyz/fennek182/dotfiles/src/branch/main/.local/bin/firefox2mpv
# Description:     Open current firefox open page in mpv by using vimium extension and dotool package

# Functionality:
# this script initiates the vimium "y y" or "y f" keystroke
# to copy current tab or give highlight selection to clipboard
# in selection mode, it waits until the clipboard has changed or 5 secs have passed

# TODO: check if firefox is in focus

open_in_mpv() {
      alacritty -e mpv "$1" > log.txt
}

case $1 in
  --current)
      #opens url from current tab
      { sleep 0.3; echo key z z; } | dotoolc
      sleep 0.2
      new_clipboard=$(wl-paste)
      cmd_string="hyprctl 'dispatch hl.dsp.exec_cmd(\"mpv "$(wl-paste)"\")'"
      eval $cmd_string
    ;;


  --select)
      # TODO: this used to work but I'm haven't checked and used it for a while
      # I'm lazy, you can try if you want :3
       { sleep 0.25; echo key z f; } | dotoolc
      current_clipboard=""
      new_clipboard=$(wl-paste)
      wl-copy ""
      i=0

      # waits 4 secs max for clipboard change (0.2s *5 = 1 sec)
      while [ $i -lt 20 ]
      do
          sleep 0.2
          let "i+=1"
          new_clipboard=$(wl-paste)
          [[ $current_clipboard != $new_clipboard ]] && echo "clipboard neu! $new_clipboard" && break
      done

      [[ $current_clipboard == $new_clipboard ]] && notify-send "keine Änderung beim Clipboard festgestellt" && exit
      open_in_mpv "$new_clipboard"
   ;;
esac
