#!/usr/bin/env zsh

export HYPRLAND_INSTANCE_SIGNATURE=$(hyprctl -j instances | jq -r '.[0] | .instance')

unset workspaces_conf
unset monitors
unset active_mon
unset active_ws_name
unset total_ws
unset workspaces
unset last_id
    

workspaces_conf="${XDG_CONFIG_HOME}/hypr/workspaces.conf"

set -x
monitors=$(hyprctl -j monitors)
active_mon=$(hyprctl -j monitors | jq --raw-output '.[] | select(.focused) | .name')
active_ws_name="$(hyprctl -j activeworkspace | jq --raw-output '.name')"
#set +x

total_ws=$(hyprctl -j workspaces | jq --compact-output --raw-output 'sort_by(.id)')
if (( $(jq length <<< "${monitors}") > 1 )); then
    workspaces="$(jq --compact-output --raw-output \
        --arg mon "${active_mon}" '[.[] | select(.monitor == $mon)]' \
        <<< "${total_ws}")"
else
    workspaces="${total_ws}"
fi
set +x

clients=$(hyprctl -j clients)

cycle_workspace () {
    set -x
    local names=$(jq --raw-output --compact-output '[.[].name]' <<< ${workspaces})
    local prev_ws=$(jq --raw-output --arg ws "${active_ws_name}" '.[index($ws) - 1]' <<< "${names}")
    local next_ws=$(jq --raw-output --arg ws "${active_ws_name}" '.[index($ws) + 1]' <<< "${names}")

    if [[ -n "${@}" ]]; then
        direction="${1}"
    else
        print "Must supply a direction!  Exiting..."  >&2
        exit 1
    fi



    #set -x
    case "${direction}" in
        prev)
            hyprctl dispatch workspace m-1
            ;;
        next)
            #if [[ "${next_ws}" != null ]]; then
                hyprctl dispatch workspace m+1
            #else
            #    hyprctl dispatch workspace "name:$(jq --raw-output '.[0]' <<< ${names})"
            #fi
            ;;
        *)
            print "Invalid direction!  Exiting..." >&2
            exit 2
            ;;
    esac
    set +x
}

add_persistent_ws () {
    set -x
    new_id=${1}; shift
    new_name=${1}; shift
    if [[ -n "${1}" ]]; then
        after_name=${1}; shift
    fi
    
    not_written=true
    tmp=$(mktemp /tmp/ws.confXXX)

    if [[ -n ${after_name} ]]; then
        while read -r line; do
            print "${line}"
            if grep -q ${after_name} <<< "${line}" && ${not_written}; then
                printf "workspace = %s, " ${new_id}
                printf "defaultName:%s, " "${new_name}"
                printf "monitor:%s, " "${active_mon}"
                print "persistent:true, default:true"
                not_written=false
            fi
        done < "${workspaces_conf}" | tee "${tmp}"
    else
        cp "${workspaces_conf}" "${tmp}"
        printf "workspace = %s, " ${new_id} | tee -a "${tmp}" 
        printf "defaultName:%s, " "${new_name}" | tee -a "${tmp}"
        printf "monitor:%s, " "${active_mon}" | tee -a "${tmp}"
        print "persistent:true, default:true" | tee -a "${tmp}"
    fi
    mv "${tmp}" "${workspaces_conf}"
    set +x
}

reorder_ws_conf () {
    set -x
    local found=false
    local new_id=${1}; shift
    local in="${1}"; shift
    
    local tmp=$(mktemp /tmp/ws.confXXX)
    while read -r line; do
        if ! ${found}; then
            print "${line}"
            if grep -q ${new_id} <<< "${line}"; then
                found=true
                old_id=${curr_id}
                new_id=$(( curr_id + 1 ))
            fi
        else
            perl -pse 's/^workspace\s*=\s*$old,\s*/workspace = $new, /' -- -old="${curr_id}" -new="${new_id}" <<< "${line}"
            old_id=${curr_id}
            curr_id=$(( curr_id + 1 ))
        fi
    done < "${in}" | tee "${tmp}"
    mv "${tmp}" "${in}"
}

create_workspace () {
    set -x
    curr_id=$(hyprctl -j activeworkspace | jq --raw-output '.id')
    last_id=$(jq '.[-1].id' <<< "${total_ws}")
    new_id=$(( last_id + 1 ))

    # save current workspace name
    print "${active_ws_name}" | \
        tee /run/user/${UID}/hypr/${HYPRLAND_INSTANCE_SIGNATURE}/last.ws

    case ${#@} in
        1)
            # add at the end
            new_name="${1}"
            shift
            add_persistent_ws ${new_id} "${new_name}"
            ;;
        2)
            new_name="${1}"; shift
            after_name="${1}"; shift
            after_id=$(jq --compact-output --raw-output --arg after "${after_name}" \
                '.[] | select(.name == $after).id' <<< "${total_ws}")
            new_id=$(( after_id + 1))
            add_persistent_ws ${new_id} "${new_name}"
            reorder_ws_conf ${new_id} "${workspaces_conf}"
            ;;
        *)
            print "Wrong number of arguments to ${0}!  Exiting..." >&2
            ;;
    esac

    hyprctl reload
    set +x
}

delete_workspace () {
    set -x
    unset old_workspace
    old_workspace="$(cat /run/user/${UID}/${HYPRLAND_INSTANCE_SIGNATURE}/last.ws)"
    sed -i "/${active_ws_name}/d" ${workspaces_conf}
    hyprctl dispatch workspace "name:${old_workspace}"
    hyprctl reload    
    set +x
}

cycle_clients () {
    hyprctl dispatch movefocus d
}
