#!/bin/bash

function usage() {
    echo -e "\nUsage:"
    echo -e " xfce4-theme-switcher [OPTION]"
    echo -e " xfce4-theme-switcher -l [THEME NAME]"
    echo -e " xfce4-theme-switcher -s [THEME NAME]"
    echo -e " xfce4-theme-switcher -d [THEME NAME]\n"
    echo -e "Change or save different thmemes for the xfce4 desktop environment.\n"
    echo -e "Options:"
    echo -e " -d\t\tdelete a theme given by the theme name"
    echo -e " -l\t\tload a theme given by the theme name"
    echo -e " -n\t\tcycle to the next theme"
    echo -e " -p\t\tcycle to the previous theme"
    echo -e " -s\t\tsave the current xfce4 settings as a theme given the theme name"
    echo -e " --list\t\tlist all themes"
    echo -e " --help\t\tdisplay this help"
    echo -e " --wal\t\tsaves pywal terminal color-scheme"
    echo -e "\t\t  must have pywal to use only used on saves"
    exit
}

function load_wal() {
    echo "Loading wal theme"
    if [ -f $CONFIG_DIR/sequences ]; then
        cp $CONFIG_DIR/sequences $HOME/.cache/wal/sequences
        ls -1 /dev/pts | while read -r terminal; do
            if [ $terminal != "ptmx" ]; then
                (cat ~/.cache/wal/sequences &) > /dev/pts/$terminal
            fi
        done
    else
        rm $HOME/.cache/wal/sequences
        #going from wal-theme terminal to normal terminal

        #ls -1 /dev/pts | while read -r terminal;
        #do
        #    if [ $terminal != "ptmx" ];
        #    then
        #        (cat ~/.config/xfce4-theme-switcher/sequencesRESET &) > /dev/pts/$terminal
        #    fi
        #done
    fi
    echo "Done"
}

function load_panel() {
    command -v xfce4-panel-profiles &> /dev/null
    if [ $? -eq 1 ]; then
        echo -e "\n!! Command \"xfce4-panel-profiles\" not found. Skipping loading panel configuration !!\n"
        return
    fi
    echo "Loading panel configuration from ${CONFIG_DIR}${name}-panel.tar.bz2"
    xfce4-panel-profiles load ${CONFIG_DIR}${name}-panel.tar.bz2 &> /dev/null
    if [ $? -eq 0 ]; then
        echo "Done"
    else
        echo "Error"
    fi
}

function load_terminalrc() {
    echo "Loading terminal settings from ${CONFIG_DIR}terminalrc"
    if [ ! -f ${CONFIG_DIR}terminalrc ]; then
        echo "Error, could not find file."
        return
    fi
    cp "${CONFIG_DIR}terminalrc" $HOME/.config/xfce4/terminal/terminalrc
    echo "Done"
}

function load_xfconf() {
    echo "Loading ${1} from ${CONFIG_DIR}${1}.conf"
    echo "${CONFIG_DIR}$1.conf" | xargs cat | while read -r line; do
        count=0
        property=""
        value=""
        for word in $line; do
            if [ $count -gt 0 ]; then
                value="${value} ${word}"
            else
                property="$property $word"
            fi
            let "count++"
        done
        property="$(echo -e "${property}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
        value="$(echo -e "${value}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
        rm $config_loc/*log &> /dev/null
        xfconf-query -c $1 -p $property -s "$value" &> /dev/null
    done
    echo "Done"
}

function load() {
    CONFIG_DIR="${DIR}${name}/"

    load_xfconf "xsettings"
    load_xfconf "xfwm4"
    load_xfconf "xfce4-desktop"
    
    load_terminalrc

    load_panel

    if [ -f $CONFIG_DIR/sequences ]; then
        load_wal
    else
        rm $HOME/.cache/wal/sequences
    fi
}

function save_wal() {
    echo "Saving wal theme"
    cp $HOME/.cache/wal/sequences $CONFIG_DIR/sequences
    echo "Done"
}

function save_panel() {
    command -v xfce4-panel-profiles &> /dev/null
    if [ $? -eq 1 ]; then
        echo -e "\n!! Command \"xfce4-panel-profiles\" not found. Skipping loading panel configuration !!\n"
        return
    fi
    echo "Saving panel configuration to ${CONFIG_DIR}${name}-panel.tar.bz2"
    xfce4-panel-profiles save "${CONFIG_DIR}${name}-panel.tar.bz2"
    echo "Done"
}

function save() {
    CONFIG_DIR="${DIR}${name}/"

    # check if .config dir exists, if not it creates it
    if [ ! -d $DIR ]; then
        echo "${DIR} not found, creating directory."
        mkdir $DIR
    fi

    # checks if theme with same name exists and asks if user would like to overwrite it
    if [ -d $CONFIG_DIR ]; then
        echo -e "Theme ${name} already exists.\nWould you like to overwrite it? [Y/n] "
        read input
        if [[ "$input" = "n" || "$input" = "N" ]]; then  # Do not overwrite; exit
            echo "Exiting..."
            exit
        fi
    else
        mkdir $CONFIG_DIR
    fi

    echo "Saving xsettings to  ${CONFIG_DIR}xsettings.conf"
    xfconf-query -c xsettings -lv > "${CONFIG_DIR}xsettings.conf"
    echo "Done"

    echo "Saving xfwm4 to ${CONFIG_DIR}xfwm4.conf"
    xfconf-query -c xfwm4 -lv > "${CONFIG_DIR}xfwm4.conf"
    echo "Done"

    echo "Saving desktop settings to ${CONFIG_DIR}xfce4-desktop.conf"
    xfconf-query -c xfce4-desktop -lv > "${CONFIG_DIR}xfce4-desktop.conf"
    echo "Done"

    echo "Saving xfce4-terminal settings to ${CONFIG_DIR}terminalrc"
    cp $HOME/.config/xfce4/terminal/terminalrc "${CONFIG_DIR}terminalrc"
    echo "Done"

    save_panel

    if [ ! -z $wal ]; then
        save_wal
    fi
}

function list() {
    for theme in $(ls ${DIR}); do
        if [ -d $DIR$theme ]; then
            echo $theme
        fi
    done
}

function delete() {
    if [ ! -d $DIR$name ]; then
        echo "Could not find theme $name"
        exit
    fi
    read -p "Are you sure you want to delete theme ${name}? [Y/n] " input
    if [[ ! "$input" = "y" && ! "$input" = "Y" ]]; then
        echo "Exiting..."
        exit
    fi
    echo "Removing theme ${name}"
    rm -rf $DIR$name
    echo "Done"
}

function next() {
    current=$(cat "${DIR}theme.current")
    array=()
    for theme in $(ls $DIR); do
        if [ -d "${DIR}$theme" ]; then
            array+=($theme)
        fi
    done
    count=0
    found=false
    for i in ${array[@]}; do
        if [ "$i" = "$current" ]; then
            break
        fi
        ((count++))
    done
    size=$((${#array[@]}-1))

    if [ $count -eq $size ]; then
        name=${array[0]}
    else
        ((count++))
        name=${array[$count]}
    fi
    load
}

function previous() {
    current=$(cat "${DIR}theme.current")
    array=()
    for theme in $(ls $DIR); do
        if [ -d "${DIR}$theme" ]; then
            array+=($theme)
        fi
    done
    count=0
    found=false
    for i in ${array[@]}; do
        if [ "$i" = "$current" ]; then
            break
        fi
        ((count++))
    done
    size=$((${#array[@]}-1))

    if [ $count -eq 0 ]; then
        name=${array[$size]}
    else
        ((count--))
        name=${array[$count]}
    fi
    load
}

###################
#                 #
# Start of script #
#                 #
###################

if [[ $* == *--wal* ]]; then  # change pywal colors
    wal=true
fi

DIR="${HOME}/.config/xfce4-theme-switcher/"
case $1 in
    -l|--load)
        name="$2"
        load
        echo $name > "${DIR}theme.current"
        ;;
    -s|--save)
        name="$2"
        save
        echo $name > "${DIR}theme.current"
        ;;
    -d|--delete)
        name="$2"
        delete
        ;;
    -n|--next)
        next
        ;;
    -p|--previous)
        previous
        ;;
    --list)
        list
        ;;
    *)
        usage
        ;;
esac
