#!/usr/bin/env bash

MONITOR1=HDMI-1
MONITOR2=DP-2


version=0.0.1

help() {
   echo "bspwm window titles"
   echo "allows you to have bspwm window titles from each monitor in your bar"
   echo "-------------------"
   echo
   echo "Syntax: bspwm_window_titles [-i <FILE_PATH>|m|p|f <FORMAT_FOCUSED|NORMAL>|V]"
   echo "options:"
   echo "h                          Print this help."
   echo "i <FILE_PATH>              Icon map path - custom path to file containing icon map"
   echo "v                          Print software version and exit."
   echo
}

add_desktop() {
  desktop_id="`cat $HOME/.cache/bspwm_focused_desktop`"
  monitor_id=$(bspc query -M -m '.focused' --names)

  current_amount=$(cat $HOME/.cache/bspwm_desktop_count_"$monitor_id")
  let new_id=current_amount+1

  max=4

  if [[ $current_amount -lt $max ]]; then
    bspc monitor $monitor_id -a "$new_id"
    echo $new_id > $HOME/.cache/bspwm_desktop_count_"$monitor_id"
  fi
}

init() {
  bspc monitor ${MONITOR1} -d 1
  bspc monitor ${MONITOR2} -d 5

  echo 1 > $HOME/.cache/bspwm_desktop_count_"$MONITOR1"
  echo 1 > $HOME/.cache/bspwm_desktop_count_"$MONITOR2"

  ### node_remove event
  ### removes empty desktops
  bspc subscribe node_remove | while read line 
  do
      monitor_id=$(echo "$line" | awk '{print $2}')
      desktop_id=$(echo "$line" | awk '{print $3}')

      windowlist=$( bspc query -N -n .window -m "$monitor_id" -d "$desktop_id" )
      desktopname=$( bspc query -D -m "$monitor_id" -d "$desktop_id" --names )

      ### check if desktop is empty
      if [[ -z "$windowlist" ]]; then
          bspc desktop -r 
      fi
  done

  ### write focused desktop id to cache file
  bspc subscribe desktop_focus | while read line 
  do
      desktop_id=$(echo "$line" | awk '{print $3}')
      echo $desktop_id > $HOME/.cache/bspwm_focused_desktop
  done

  ### write desktop amount to cache file
  bspc subscribe desktop_add | while read line 
  do
      monitor_id=$(echo "$line" | awk '{print $2}')
      monitor_name $(bspc query -M -m "$monitor_id" --names)
      desktop_id=$(echo "$line" | awk '{print $3}')
      desktops=$(bspc query -D -m "$monitor_id" --names)

      count=0
      echo "$desktops" | sed 's/ //g' | while read l
      do
          ((count++))
          echo $count
          echo $count > $HOME/.cache/bspwm_desktop_count_"$monitor_name"
      done
  done
}

while getopts ":haiv:" option; do
   case $option in
      h)
        help
        exit;;
      a)
        add_desktop
        exit;;
      i)
        init
        exit;;
      v)
        echo "Version $version";
        exit;;
      *)
        echo "Error: Invalid option"
        exit;;
   esac
done

help
exit


