#!/bin/bash

# cortilectl - helper script for cortile tiling manager

# Cortile config file
CONFFILE="$HOME/.config/cortile/config.toml"
IMG_DIR="$HOME/.config/cortile/tint2-cortile"

start() {
	echo "">/tmp/cortile.log
    cortile -v &
}

stop() {
 pkill cortile 
}

editconf() {
    xdg-open ${CONFFILE}
}

sendcmd(){
	#notify-send.sh "$1" "aaa"
	case "$1" in
	proportion_increase) echo '{"Action":"proportion_increase"}' | nc -U /tmp/cortile.sock.in &2>/dev/null;;
	proportion_decrease) echo '{"Action":"proportion_decrease"}' | nc -U /tmp/cortile.sock.in &2>/dev/null;;
	window_next) echo '{"Action":"window_next"}' | nc -U /tmp/cortile.sock.in &2>/dev/null;;
	window_previous) echo '{"Action":"window_previous"}' | nc -U /tmp/cortile.sock.in &2>/dev/null;;
	esac
}

is_tiled(){
	grep workspace-$(xdotool get_desktop) /tmp/cortile.log |tail -n 1 |grep Tile >/dev/null
}
is_fullscreen(){
	grep workspace-$(xdotool get_desktop) /tmp/cortile.log |tail -n 1 |grep fullscreen >/dev/null
}
get_current_layout(){
	layout=$(grep workspace-$(xdotool get_desktop) /tmp/cortile.log |tail -n 1| cut -d' ' -f6)
	case "$layout" in
	vertical-right) echo ${IMG_DIR}/vertical-right.png;;
	vertical-left) echo ${IMG_DIR}/vertical-left.png;;
	horizontal-top) echo ${IMG_DIR}/horizontal-top.png;;
	horizontal-bottom) echo ${IMG_DIR}/horizontal-bottom.png;;
	fullscreen) echo ${IMG_DIR}/fullscreen.png;;
	esac
}
main(){
if ! pgrep -x cortile >/dev/null ;then exit 0;fi
if is_tiled ;then
	get_current_layout
else
	echo "${IMG_DIR}/untiled.png"
fi
}

left(){
if is_tiled ;then
	if is_fullscreen ;then
	#sendkey untile
	echo "${IMG_DIR}/untiled.png"
	echo '{"Action":"untile"}' | nc -U /tmp/cortile.sock.in &2>/dev/null
	else
	#sendkey layout_cycle
	echo '{"Action":"cycle_next"}' | nc -U /tmp/cortile.sock.in &2>/dev/null
	get_current_layout
	fi
else
	#sendkey tile
	echo '{"Action":"tile"}' | nc -U /tmp/cortile.sock.in
	echo '{"Action":"layout_vertical_left"}' | nc -U /tmp/cortile.sock.in
	get_current_layout
	fi
}
middle(){
echo '{"Action":"toggle"}' | nc -U /tmp/cortile.sock.in  &2>/dev/null

if is_tiled ;then
get_current_layout
else
echo "${IMG_DIR}/untiled.png"
fi
}
right(){
: #menu
}
up(){
if is_tiled; then
	if is_fullscreen ;then
		sendcmd window_previous
	else
		sendcmd proportion_increase
	fi
else
xdotool set_desktop --relative 1
fi
}
down(){	
if is_tiled; then
	if is_fullscreen ;then
		sendcmd window_next
	else	
		sendcmd proportion_decrease
	fi
else
xdotool set_desktop --relative -- -1
fi	
}

case "$1" in 
    start) start;;
    stop) stop;;
    editconf) editconf;;
    left)left;;
	right)right;;
	middle)middle;;
	up)up;;
	down)down;;
	*)main;;
esac
