#!/bin/bash
#
#    colorizer - set of tools for Mabox (auto)theming
#    Copyright (C) 2022-2026 Daniel Napora    <danieln@maboxlinux.org>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
. /usr/share/mb-jgtools/jgtools.inc



PR_WINID=$(wmctrl -lp |grep 'PyRadio: \|PyRadio -'|cut -d' ' -f1)
wmctrl -iR ${PR_WINID}

if [[ ! -f "$HOME"/local/share/applications/pyradio.desktop ]];then
	pyradio --terminal terminator > /dev/null 2>&1
fi

me="colorizer-pyradio -s"

THEMERC=~/.config/pyradio/themes/mbcolors.pyradio-theme

# get wallpaper color palette
WALLPALDIR="$HOME/.cache/colorizer/palettes"
mkdir -p "$WALLPALDIR"
read WALLPATH<<< $(grep file "$HOME"/.config/nitrogen/bg-saved.cfg | tail -1 | cut -d'=' -f2)

NAME=${WALLPATH////_}
if [[ "${NAME}" =~ ^_home_.* ]]; then
n=${#HOME}
((n++))
NAME=${NAME:${n}}
fi
if [ ! -f "$WALLPALDIR/$NAME.clr" ]; then
convert ${WALLPATH} -resize 25% -colors 16 -unique-colors txt:- |grep -v '^#'| awk '{print substr($3,1,7)}' |pastel sort-by brightness |pastel format hex > "$WALLPALDIR/$NAME.clr"
fi
mapfile -t w < "$WALLPALDIR/$NAME.clr"
if [[ "${#w[@]}" -lt 8 ]]; then
w+=("#2e3440" "#4c566a" "#5e81ac" "#bf616b" "#b48ead" "#a3be8c" "#ebcb8b" "#d8dee9" "#eceff4")
fi



case "$LANG" in
    pl*)
    COLORIZE_PYRADIO="Pokoloruj PyRadio"
    START_PYRADIO="Uruchom PyRadio"
    INFO="Ważna informacja"
    INFO_HEAD="Jak działa automatyczna zmiana kolorów?"
    INFO_TXT="Automatyczna zmiana kolorów działa z motywem <b>mbcolors</b> (User theme).\nAby go ustawić:\n- użyj klawisza <b>t</b> - wybór motywów\n- zaznacz motyw <i>mbcolors</i> i naciśnij <b>spację</b> - (ustawia jako domyślny)\n- wciśnij <b>c</b> - aby włączyć śledzenie zmian w pliku motywu.\n\n"
    GENERATEFROMWP="Generuj z kolorów tapety..."
    LIGHTBG="Jasne tło"
    DARKBG="Ciemne tło"
    SETCOLORS="Ustaw kolory..."
    RESETTHEME="Resetuj motyw"
    EXPORTTHEME="<b>Eksportuj</b> jako nowy motyw"
    CONFIG_AND_DOCS="Konfiguracja i Dokumentacja"
    README="PyRadio CZYTAJTO"
    MANUAL="Manual PyRadio"
    EDITCONF="Edytuj plik konfiguracyjny"
    EDITSTATIONS="Edytuj listę stacji"
    CONFIGDIR="Katalog z konfiguracją"
    _COLORIZER_ROOT="<b>Colorizer</b> - menu główne"
    ;;
    *)
    COLORIZE_PYRADIO="Colorize PyRadio"
    START_PYRADIO="Start PyRadio"
    INFO="Info (important)"
    INFO_HEAD="How it works?"
    INFO_TXT="Automatic theme generation works with <b>mbcolors</b> user theme.\n Configuration:\n- use <b>t</b> key to show theme selection dialog\n- navigate to <i>mbcolors</i> theme and press <b>c</b>\n\n"
    GENERATEFROMWP="Generate from wallpaper colors..."
    LIGHTBG="Light Background"
    DARKBG="Dark Background"
    SETCOLORS="Set colors individually..."
    RESETTHEME="Reset theme"
    EXPORTTHEME="<b>Export</b> as new theme"
    CONFIG_AND_DOCS="Config and Docs"
    README="PyRadi README"
    MANUAL="PyRadio Manual"
    EDITCONF="Edit config file"
    EDITSTATIONS="Edit stations list"
    CONFIGDIR="Config Dir"
    _COLORIZER_ROOT="<b>Colorizer</b> rootmenu"
    ;;
esac

getvalues () {
read S SFG SBG<<< "$(grep '^Stations ' ${THEMERC})"
read AS1 AS2 ASFG<<< "$(grep '^Active Station ' ${THEMERC})"
read SB1 SB2 SBFG SBBG<<< "$(grep '^Status Bar ' ${THEMERC})"
read NC1 NC2 NCFG NCBG<<< "$(grep '^Normal Cursor ' ${THEMERC})"
read AC1 AC2 ACFG ACBG<<< "$(grep '^Active Cursor ' ${THEMERC})"
read EC1 EC2 ECFG ECBG<<< "$(grep '^Edit Cursor ' ${THEMERC})"
read EF1 EF2 EFFG<<< "$(grep '^Extra Func ' ${THEMERC})"
read PURL1 PURL2 PURLFG<<< "$(grep '^PyRadio URL ' ${THEMERC})"
read MB1 MB2 MBFG<<< "$(grep '^Messages Border ' ${THEMERC})"

}
    getvalues

    out+=("^sep($COLORIZE_PYRADIO)")
    #out+=("$START_PYRADIO,terminator --geometry=420x440-20-20 -e pyradio")
    if pgrep -f "/usr/bin/python /usr/bin/pyradio" >/dev/null ;then
    :
    else
	out+=("$START_PYRADIO	<span bgcolor='#333333' color='#d3d3d3'>  <small>W + r</small>  </span>,xdotool key super+r;$me")
	#out+=("PYRADIO	<span bgcolor='#333333' color='#d3d3d3'>  <small>W + r</small>  </span>,gtk-launch pyradio;sleep 1;$me")
	fi
    
    
    out+=("<big></big>   $INFO,notify-send.sh -i pyradio -u critical '$INFO_HEAD' '$INFO_TXT'")
    
    out+=("^sep($SETCOLORS)")
    out+=("<tt><span weight='bold' bgcolor='$SBG' fgcolor='$SFG'>  AbCd   </span></tt>  Stations,^checkout(stations)")
    out2+=("^tag(stations)")
    out2+=("^sep(Stations)")
    out2+=("<tt><span weight='bold' bgcolor='$SBG' fgcolor='$SFG'>  AbCd   </span></tt>  Text,^pipe(mbclr '$SFG' prtctl stations_txt 'Stations Text' '$me')")
    out2+=("<tt><span weight='bold' bgcolor='$SBG' fgcolor='$SFG'>         </span></tt>  Background,^pipe(mbclr '$SBG' prtctl stations_bg 'Stations Background' '$me')")
    
    out+=("<tt><span weight='bold' bgcolor='$SBG' fgcolor='$ASFG'>  AbCd   </span></tt>  Active Station (text),^pipe(mbclr '$ASFG' prtctl active_station ACTIVE_STATION '$me')")
    
    out+=("<tt><span weight='bold' bgcolor='$NCBG' fgcolor='$NCFG'>  AbCd   </span></tt>  Normal Cursor,^checkout(normalcursor)")
    out2+=("^tag(normalcursor)")
    out2+=("^sep(Normal Cursor)")
    out2+=("<tt><span weight='bold' bgcolor='$NCBG' fgcolor='$NCFG'>  AbCd   </span></tt>  Text,^pipe(mbclr '$NCFG' prtctl normal_cursor_txt 'Normal Cursor Text' '$me')")
    out2+=("<tt><span weight='bold' bgcolor='$NCBG' fgcolor='$NCFG'>         </span></tt>  Background,^pipe(mbclr '$NCBG' prtctl normal_cursor_bg 'Normal Cursor Background' '$me')")
    
    out+=("<tt><span weight='bold' bgcolor='$ACBG' fgcolor='$ACFG'>  AbCd   </span></tt>  Active Cursor,^checkout(activecursor)")
    out2+=("^tag(activecursor)")
    out2+=("^sep(Active Cursor)")
    out2+=("<tt><span weight='bold' bgcolor='$ACBG' fgcolor='$ACFG'>  AbCd   </span></tt>  Text,^pipe(mbclr '$ACFG' prtctl active_cursor_txt 'Active Cursor Text' '$me')")
    out2+=("<tt><span weight='bold' bgcolor='$ACBG' fgcolor='$ACFG'>         </span></tt>  Background,^pipe(mbclr '$ACBG' prtctl active_cursor_bg 'Active Cursor Background' '$me')")
    
    
    out+=("<tt><span weight='bold' bgcolor='$ECBG' fgcolor='$ECFG'>  AbCd   </span></tt>  Edit Cursor,^checkout(editcursor)")
    out2+=("^tag(editcursor)")
    out2+=("^sep(Edit Cursor)")
    out2+=("<tt><span weight='bold' bgcolor='$ECBG' fgcolor='$ECFG'>  AbCd   </span></tt>  Text,^pipe(mbclr '$ECFG' prtctl edit_cursor_txt 'Edit Cursor Text' '$me')")
    out2+=("<tt><span weight='bold' bgcolor='$ECBG' fgcolor='$ECFG'>         </span></tt>  Background,^pipe(mbclr '$ECBG' prtctl edit_cursor_bg 'Edit Cursor Background' '$me')")
    
    out+=("<tt><span weight='bold' bgcolor='$SBBG' fgcolor='$SBFG'>  AbCd   </span></tt>  Status Bar,^checkout(statusbar)")
    out2+=("^tag(statusbar)")
    out2+=("^sep(Status Bar)")
    out2+=("<tt><span weight='bold' bgcolor='$SBBG' fgcolor='$SBFG'>  AbCd   </span></tt>  Text,^pipe(mbclr '$SBFG' prtctl status_bar_txt 'Status Bar Text' '$me')")
    out2+=("<tt><span weight='bold' bgcolor='$SBBG' fgcolor='$SBFG'>         </span></tt>  Background,^pipe(mbclr '$SBBG' prtctl status_bar_bg 'Status Bar Background' '$me')")
    out+=("<tt><span weight='bold' bgcolor='$SBG' fgcolor='$EFFG'>  AbCd   </span></tt>  Extra Func,^pipe(mbclr '$EFFG' prtctl extra_func EXTRA_FUNC '$me')")
    out+=("\"\"\"<tt><span weight='bold' bgcolor='$SBG' fgcolor='$PURLFG'>  AbCd   </span></tt>  Group, PyRadio URL\"\"\",^pipe(mbclr '$PURLFG' prtctl pyradio_url 'PyRadio URL' '$me')")
    out+=("<tt><span weight='bold' bgcolor='$SBG' fgcolor='$MBFG'>_________</span></tt>  Messages Border,^pipe(mbclr '$MBFG' prtctl messages_border 'Messages Border' '$me')")
    
    out+=("^sep(<i>$GENERATEFROMWP</i>)")
    out+=("<tt><span bgcolor='${w[-1]}' fgcolor='${w[4]}'> 1. station </span></tt>  $LIGHTBG,w2theme pyradio light;$me")
    out+=("<tt><span bgcolor='${w[0]}' fgcolor='${w[-3]}'> 2. station </span></tt>  $DARKBG,w2theme pyradio dark;$me")
    
    out+=("^sep()")
    out+=("<big>󰑤</big>   $RESETTHEME,prtctl resettheme;$me")
    out+=("^sep()")
    out+=("$EXPORTTHEME,prtctl exp;$me")
    
    out+=("^sep($CONFIG_AND_DOCS)")
    #out+=("PyRadio README,cat /usr/share/doc/pyradio/README.html| yad --html --no-buttons --no-escape --height=800 --width=600")
    out+=("<big></big>   $README,xdg-open /usr/share/doc/pyradio/README.html")
    out+=("<big></big>   $MANUAL,^term(man pyradio)")
    out+=("^sep()")
    out+=("<big></big>   $EDITCONF,xdg-open ~/.config/pyradio/config")
    out+=("<big></big>   $EDITSTATIONS,xdg-open ~/.config/pyradio/stations.csv")
    out+=("^sep()")
    out+=("<big></big>   $CONFIGDIR,^pipe(jgbrowser ~/.config/pyradio)")


### RUN
if [[ "$1" == "-s" ]]; then
    
    CNF_DIR="$HOME/.config/colorizer"
    CNF_FILE="$CNF_DIR/colorizer.conf"
    source "$CNF_FILE"

    out+=("^sep()")
    out+=(" ${arrow_string_left}    $_COLORIZER_ROOT,colorizer -s")
    
    if [[ "$colorizer_size" == "full" ]];then
    eval $(xdotool getdisplaygeometry --shell)
    MENU_HEIGHT_MIN="$HEIGHT"
    MENU_HEIGHT_MAX=$MENU_HEIGHT_MIN
    jgtools_radius=0
    menu_margin_x="0"
    else
    MENU_VALIGN="center"
    menu_margin_x=${submenu_spacing:-0}
    fi
    

    MENU_HALIGN="left"
    jgmenu_icon_size=0
    
    [ $(pidof picom) ] && MENU_RADIUS=$jgtools_radius
    [ -z $jgmenu_use_borders ] && menu_border=0
    JGWIDTH=$((jgtools_padding + 270 + jgtools_padding))
    MENU_PADDING_TOP=$((jgtools_padding + 152))
    
    #WALLPAPER
    read WALLPATH<<< $(grep file "$HOME"/.config/nitrogen/bg-saved.cfg |  tail -1 | cut -d'=' -f2)
    THUMBDIR="$HOME/.cache/colorizer/thumbs"
    mkdir -p ${THUMBDIR}
    NAME=${WALLPATH////_}
    if [[ "${NAME}" =~ ^_home_.* ]]; then
        n=${#HOME}
        ((n++))
        NAME=${NAME:${n}}
    fi
    THUMB="${THUMBDIR}/${NAME}.png"
    if [[ ! -f "$THUMB" ]]
        then
        convert ${WALLPATH} -resize 270x150^ -gravity center -extent 270x150 ${THUMB}
    fi
    
    mkconfigfile

cat <<EOF > ${MENU_ITEMS}
@icon,,$((jgtools_padding)),$((jgtools_padding)),270,150,4,left,top,,,${THUMB}
#@icon,,$((jgtools_padding + 4)),$((jgtools_padding + 4)),270,150,4,left,top,,,/usr/share/mabox-colorizer/img/colorizer-conky.png
@rect,,$((jgtools_padding+4)),$((jgtools_padding + 112)),262,34,0,left,top,#222222 20,#222222 70,
@text,,$((jgtools_padding + 144)),$((jgtools_padding + 116)),120,30,0,left,top,#FFFFFF ,${WINCLR},<span size='10400' font_family='Ubuntu'><b>PyRadio</b> Colorizer</span>


$(printf '%s\n' "${out[@]}")
$(printf '%s\n' "${out2[@]}")
EOF

    jgmenu --config-file=${CONFIG_FILE} --csv-file=${MENU_ITEMS} 2>/dev/null
    exit 0
fi

printf '%s\n' "${out[@]}"
printf '%s\n' "${out2[@]}"

