#!/usr/bin/env nu

module ipc {

def ipcCmd [] {
if (is-sway) {
   "swaymsg"
} else if (is-i3) {
   "i3-msg"
} else {
   error make { msg: "This script only supports sway or i3" }
}
}

def is-sway [] {
    ("SWAYSOCK" in $env)
}

def is-i3 [] {
    ("I3SOCK" in $env)
}

export def ipc-cmd [--raw, ...parameters: string] {
    let result = (run-external (ipcCmd) ...$parameters)
    if $raw {
       $result
    } else {
       $result | from json
    }
}
}

use ipc ipc-cmd

def workspaces [] {
    let workspaces = (ipc-cmd "-t" "get_workspaces" | select id name focused urgent visible)
    let mode = (ipc-cmd "-t" "get_binding_state")
    let focused_title_full = ((ipc-cmd --raw "-t" "get_tree") | jaq -r '.. | (.nodes? // empty)[] | select(.focused) | {name}' | from json).name
    mut focused_title = ($focused_title_full | str substring -g 0..150)
  
    if ($focused_title_full | str length) > 150 {
      $focused_title = ($focused_title | append "..." | str join "")
    }
    
  { workspaces: $workspaces, mode: $mode.name, title: $focused_title } 
}

def main [] {
    print (workspaces | to json -r)
    loop {
         ipc-cmd --raw '-t' 'subscribe' '["workspace","window","mode"]' out+err> /dev/null
         try {
             print (workspaces | to json -r)
         }
    }
}