#!/bin/bash

JSON_PATH=~/.shellconfig/workspaces/workspaces.json

WSP=$(cat ${JSON_PATH} \
    | jq  -r 'keys[]' \
    | fzf --reverse --header "🖥 Select a Workspace to open:"
)

if [ -z "$WSP" ]; then
    echo "Aborted"
    exit 1
fi

DIR=$(cat ${JSON_PATH} \
    | jq -r --arg WSP "${WSP}" '.[$WSP]|.["dir"]' \
    | tr -d '\r'
)
LAYOUT=$(cat ${JSON_PATH} \
    | jq -r --arg WSP "${WSP}" '.[$WSP]|.["layout"]' \
    | tr -d '\r'
)
IS_CMD=$(cat ${JSON_PATH} \
    | jq -r --arg WSP "${WSP}" '.[$WSP]|.["is_cmd"] // 0' 
)
cd "$DIR"

LAYOUT_ARGS=$(echo $LAYOUT | grep -oP "(?<=layout ).*(?)")
echo $LAYOUT_ARGS

tmux neww
if [ $IS_CMD -eq 1 ]; then
    tmux send-keys "${LAYOUT}" C-m
    tmux rename-window "${WSP}"
elif [ ! -z $IS_LAYOUT ]; then
    tmux send-keys "layout '${LAYOUT_ARGS}' '${WSP}'"
else
    tmux send-keys "${LAYOUT} '${WSP}'" C-m
fi



