#!/bin/sh

if [[ $# -eq 0 ]] ; then
    echo "i3-workspace-layout [ name workspace | list | define workspace name | edit name | dmenu ]"
    exit
fi

LAYOUT=$1
WORKSPACE=$2

function define_workspace {
    i3-save-tree --workspace ${WORKSPACE} > ~/.config/i3/layouts/${NAME}.json
    emacsclient --alternate-editor="" -n ~/.config/i3/layouts/${NAME}.json
}

function edit_workspace {
    emacsclient --alternate-editor="" -n ~/.config/i3/layouts/${WORKSPACE}.json
}

function list_workspaces {
    for layout in ~/.config/i3/layouts/*.json ;
    do
        echo "$(basename -- ${layout} .json)"
    done
}

function apply_workspace {
    if [[ -e ~/.config/i3/layouts/${LAYOUT}.json ]] ; then
        i3-msg "append_layout ~/.config/i3/layouts/${LAYOUT}.json"
        [[ -e ~/.config/i3/layouts/${LAYOUT}.after ]] && sh ~/.config/i3/layouts/${LAYOUT}.after
    else
        i3-nagbar -m "${LAYOUT} not available" -t error
    fi
}

function apply_workspace_number {
    # i3-msg "workspace number ${WORKSPACENUMBER}"
    if [[ -e ~/.config/i3/layouts/${LAYOUT}.json ]] ; then
        i3-msg "workspace \"${WORKSPACE}\"; append_layout ~/.config/i3/layouts/${LAYOUT}.json"
        [[ -e ~/.config/i3/layouts/${LAYOUT}.after ]] && sh ~/.config/i3/layouts/${LAYOUT}.after
    else
        i3-nagbar -m "${LAYOUT} not available" -t error
    fi
}

function with_external_completion {
    if [[ -e `which rofi` ]] ; then
        LAYOUT=`list_workspaces | rofi -dmenu -p "workspace layout"`
        [[ $LAYOUT != "" ]] && apply_workspace
    else
        LAYOUT=`list_workspaces | dmenu -p "workspace layout:"`
        [[ $LAYOUT != "" ]] && apply_workspace
    fi
}

case ${LAYOUT} in
    define)
        NAME=$3
        define_workspace
        ;;
    edit)
        edit_workspace
        ;;
    list)
        list_workspaces
        ;;
    dmenu)
        with_external_completion
        ;;
    *)
        if [[ $WORKSPACE != "" ]] ; then
            apply_workspace_number
        else
            apply_workspace
        fi
esac
