#! /bin/bash
data=/usr/share/tromjaro-layout-switcher
icons=$data/icons
profiles=$data/profiles

enable-top-bar-integration() {
    # Enable global menus
    pacman -Qq vala-panel-appmenu-registrar ||
        zensu SKIP_AUTOSNAP= pacman -S --noconfirm vala-panel-appmenu-registrar ||
        { notify-send 'Error' 'Failed installing vala-panel-appmenu-registrar !\nmake sure that you typed the password correctly or that you are not currently installing or updating your system\nEnabling the internet connection might solve the issue'; exit; }
    pacman -Qq vala-panel-appmenu-registrar || exit

    # Hide window borders when maximized
    xfconf-query -c xfwm4 -p /general/borderless_maximize -n -t bool -s true
    # Hide top bar of windows when maximized
    xfconf-query -c xfwm4 -p /general/titleless_maximize -n -t bool -s true
    # Put window buttons on left side
    xfconf-query -c xfwm4 -p /general/button_layout -n -t string -s "CMH|"
}

disable-top-bar-integration() {
    # Disable global menus
    ! pacman -Qq vala-panel-appmenu-registrar ||
        zensu SKIP_AUTOSNAP= pacman -R --noconfirm vala-panel-appmenu-registrar ||
        { notify-send 'Error' 'Failed removing vala-panel-appmenu-registrar !\nmake sure that you typed the password correctly or that you are not currently installing or updating your system'; exit; }
    pacman -Qq vala-panel-appmenu-registrar && exit
    killall appmenu-registrar

    # Hide window borders when maximized
    xfconf-query -c xfwm4 -p /general/borderless_maximize -n -t bool -s true
    # Don't hide top bar of windows when maximized
    xfconf-query -c xfwm4 -p /general/titleless_maximize -n -t bool -s false
    # Put window buttons on right side
    xfconf-query -c xfwm4 -p /general/button_layout -n -t string -s "|HMC"
}

choice=$(
yad --no-buttons --center --keep-icon-size --separator='' --use-interp --title 'TROMjaro Layout Switcher' --text-align=center --text 'Changing to or from any layout that has global menus, will require your admin password' --form --columns 3 \
--field=!"$icons/windows.png"!'Windows-Like':BTN "kill -USR1 \$YAD_PID; echo -n 'Windows-Like'" \
--field=!"$icons/macos.png"!'MacOS-Like':BTN "kill -USR1 \$YAD_PID; echo -n 'MacOS-Like'" \
--field=!"$icons/mx.png"!'MX-Like':BTN "kill -USR1 \$YAD_PID; echo -n 'MX-Like'" \
--field=!"$icons/gnome.png"!'Gnome-Like':BTN "kill -USR1 \$YAD_PID; echo -n 'Gnome-Like'" \
--field=!"$icons/unity.png"!'Unity-Like (default)':BTN "kill -USR1 \$YAD_PID; echo -n 'Unity-Like'" \
--field=!"$icons/topx.png"!'TopX-Like':BTN "kill -USR1 \$YAD_PID; echo -n 'TopX-Like'"
)

case "$choice" in
    'Windows-Like'|'MX-Like'|'Gnome-Like'|'TopX-Like')
        disable-top-bar-integration ;;
    'Unity-Like'|'MacOS-Like')
        enable-top-bar-integration ;;
    *) exit ;;
esac

# Apply the XFCE panel profiles for the chosen layout
xfce4-panel-profiles load "$profiles/$choice.tar.bz2"

sleep 2.5 && notify-send "$choice layout was enabled"