#!/usr/bin/bash

cd ~/.config/eww

getwins() {
  hyprctlclients=$(hyprctl clients -j \
    | grep -v '"mapped": ' \
    | grep -v '"hidden": ' \
    | grep -v '"floating": ' \
    | grep -v '"monitor": ' \
    | grep -v '"pid": ' \
    | grep -v '"xwayland": ' \
    | grep -v '"pinned":' \
    | grep -v '"fullscreen": ' \
    | grep -v '"fullscreenMode": ' \
    | grep -v '"fakeFullscreen": ' \
    | grep -v '"grouped": ')

  # echo $hyprctlclients | gojq -c '.[]'

  IFS=$'\n'
  clientsarr=( $(echo $hyprctlclients | gojq -c -M '.[]') )

  #For every window
  for client in "${clientsarr[@]}"; do
    iconpath=''
    clientclass=$(echo "$client" | gojq -r '.class')
    if [[ "$clientclass" == "" ]]; then 
      continue
    fi

    # Get app icon
    if [ -f "scripts/cache/$clientclass" ]; then
        iconpath=$(cat scripts/cache/$clientclass)
        if [ ! -f "${iconpath}" ]; then # Cache refresh if icon doesnt exist
            iconpath=$(geticons -t $(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g") "$clientclass" | head -n 1)
            echo "${iconpath}" > "scripts/cache/$clientclass"
        fi
    else
        iconpath=$(geticons -t $(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g") "$clientclass" | head -n 1)
        echo "${iconpath}" > "scripts/cache/$clientclass"
    fi
    if [[ ${iconpath} == "" ]]; then
      # Retry with lowercase if icon not found
      iconpath=$(geticons -t $(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g") $(echo "$clientclass" | tr '[:upper:]' '[:lower:]' | sed 's/\ /-/g') | head -n 1)

      if [[ ! ${iconpath} = "" ]]; then
        rm "scripts/cache/$clientclass"
        echo "${iconpath}" > "scripts/cache/$clientclass"
      else 
        newname=$(scripts/iconpatch $clientclass)
        iconpath=$(geticons -t $(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g") "$newname" | head -n 1)
        if [[ ! ${iconpath} = "" ]]; then
          rm "scripts/cache/$clientclass"
          echo "${iconpath}" > "scripts/cache/$clientclass"
        else
          # Fallback app icon, replace the path below to the fallback icon of your choice
          # iconpath="/usr/share/icons/Win11-dark/mimes/48/application-x-executable.svg"
          iconpath=$(geticons -t $(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g") "application-x-executable" | head -n 1)
          rm "scripts/cache/$clientclass"
          echo "${iconpath}" > "scripts/cache/$clientclass"
        fi
      fi
    fi
  done
}

# Do stuff here
getwins

if [ "$1" == "--once" ]; then
  exit 0
else
  socat -u UNIX-CONNECT:/tmp/hypr/"$HYPRLAND_INSTANCE_SIGNATURE"/.socket2.sock - | rg --line-buffered "window>>" | while read -r line; do
    getwins
  done
fi