#!/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

wmctrl -R cavatransparent

me="colorizer-cava -s"

CFGFILE=~/.config/cava/config

# 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*)
    INFO="Cava porady"
    COLORIZE_CAVA="Pokoloruj Cava"
    COLOR="Jednolity kolor"
    REVERSE_GRADIENT="Odwróć kolory gradientu"
    START_CAVA="Uruchom Cava"
    STOP_CAVA="Zakończ Cava"
    CAVA_SIZE="Cava wymiary (okna)"
    CWIDTH="Szerokość"
    CHEIGHT="Wysokość (px)"
    GENERATEFROMWP="Generuj z kolorów tapety..."
    LIGHTBG="Jasne do ciemnego"
    DARKBG="Ciemne do jesnego"
    BARS="Słupki"
    BAR_WIDTH="Szerokość słupków"
    BAR_SPACING="Odstęp..."
    COLOR_MODE="Tryb kolorowania"
    SOLID_COLOR="Jednolity kolor"
    GRADIENT="Gradient"
    PREGRADIENT="Zastosuj gotowy gradient"
    MODGRAD_FROM="Gradient kolor 1"
    MODGRAD_TO="Gradient kolor 2"
    _GENERAL="Ogólne"
    _FRAMERATE="Ramki (fps)"
    _NOISE_RED="Redukcja szumów"
    _RESETCFG="Resetuj konfigurację"
    EDITCONF="Edytuj plik konfiguracyjny"
    RELOAD="Przeładuj konfigurację"
    RELOAD_COLORS="Przeładuj kolory"
    _COLORIZER_ROOT="<b>Colorizer</b> - menu główne"
    ;;
    *)
    INFO="CaVa tips &amp; tricks"
    COLORIZE_CAVA="Colorize Cava"
    COLOR="Solid Color"
    REVERSE_GRADIENT="Reverse gradient's colors"
    START_CAVA="Start Cava"
    STOP_CAVA="Stop Cava"
    CAVA_SIZE="Cava (window) size"
    CWIDTH="Width"
    CHEIGHT="Height (px)"
    GENERATEFROMWP="Generate from wallpaper colors..."
    LIGHTBG="Light to Dark"
    DARKBG="Dark to Light"
    BARS="Bars"
    BAR_WIDTH="Bar width"
    BAR_SPACING="Bar spacing"
    COLOR_MODE="Color mode"
    SOLID_COLOR="Solid color"
    GRADIENT="Gradient"
    PREGRADIENT="Apply predefined gradient"
    MODGRAD_FROM="Modify Gradient From"
    MODGRAD_TO="Modify Gradient To"
    _GENERAL="General"
    _FRAMERATE="Framerate"
    _NOISE_RED="Noise reduction"
    _RESETCFG="Reset config to default"
    EDITCONF="Edit config file"
    RELOAD="Reload config"
    RELOAD_COLORS="Reload colors only"
    _COLORIZER_ROOT="<b>Colorizer</b> rootmenu"
    ;;
esac

getvalues () {
read NOISE_RED <<< "$(grep '^noise_reduction ' ${CFGFILE} | cut -d"=" -f2)"
read FPS <<< "$(grep '.*framerate ' ${CFGFILE} | cut -d"=" -f2)"

read FG <<< "$(grep '.*foreground ' ${CFGFILE} | cut -d"'" -f2)"
read BW <<< "$(grep '.*bar_width ' ${CFGFILE} | cut -d"=" -f2)"
read BS <<< "$(grep '.*bar_spacing ' ${CFGFILE} | cut -d"=" -f2)"
read GR <<< "$(grep '.*gradient ' ${CFGFILE} | cut -d"=" -f2)"
read GR_FROM <<< "$(grep '.*gradient_color_1 ' ${CFGFILE} | cut -d"'" -f2)"
read GR_TO <<< "$(grep '.*gradient_color_3 ' ${CFGFILE} | cut -d"'" -f2)"


if [ ${#FG} != 7 ];then
FGC="#59cc33"
else
FGC=${FG}
fi
FGT=$(pastel textcolor ${FGC}|pastel format hex)
}
    getvalues
    pgrep -f cavatransparent > /dev/null && out+=("<big>󰺢</big>   $STOP_CAVA,mb-music cavakill;$me") || out+=("<big>󰺢</big>   $START_CAVA,mb-music cavastart;$me")
    out+=("^sep()")
    cwidth=${cava_width:-half}
    cheight=${cava_height:-200}
    out+=("$CAVA_SIZE,^checkout(size)")
    out2+=("^tag(size)")
    out2+=("^sep($CWIDTH)")
    for i in full half third
    do
    [[ "${cwidth}" == "${i}" ]] && out2+=("<big>${ron}</big>   <b>$i</b>,cavactl start $i;$me") || out2+=("<big>${roff}</big>   $i,cavactl start $i;$me")
    done
    out2+=("^sep($CHEIGHT)")
    for i in 200 100 50
    do
    [[ "${cheight}" == "${i}" ]] && out2+=("<big>${ron}</big>   <b>$i</b>,cavactl start $i;$me") || out2+=("<big>${roff}</big>   $i,cavactl start $i;$me")
    done
        
    out+=("^sep($COLOR_MODE)")
    [[ "$GR" == "0" ]] && out+=("<big>${ron}</big>  $SOLID_COLOR,cavactl mode solid;$me" "<big>󰝦</big>  $GRADIENT,cavactl mode gradient;$me") || out+=("<big>󰝦</big>  $SOLID_COLOR,cavactl mode solid;$me"  "<big>${ron}</big>  $GRADIENT,cavactl mode gradient;$me")
    out+=("^sep($COLORIZE_CAVA)")
    out+=("<tt><span bgcolor='$FGC' fgcolor='$FGT'>  ${FGC}  </span></tt>  $COLOR,^pipe(mbclr '$FGC' cavactl foreground Cava_Bar_Color '$me')")
    out+=("^sep($GRADIENT)")
    out+=("<span bgcolor='$GR_FROM'>     </span><span bgcolor='$GR_TO'>     </span>  $PREGRADIENT,^pipe(mbgrad cava)")
    out+=("<span bgcolor='$GR_TO'>     </span><span bgcolor='$GR_FROM'>     </span>  $REVERSE_GRADIENT,cavactl gradient '${GR_TO}' '${GR_FROM}';$me")
    out+=("^sep()")
    out+=("<tt><span bgcolor='$GR_FROM'>    </span></tt>  $MODGRAD_FROM,^pipe(mbclr '$GR_FROM' cavactl grad_from Cava_Grad_From_Color '$me')")
    out+=("<tt><span bgcolor='$GR_TO'>    </span></tt>  $MODGRAD_TO,^pipe(mbclr '$GR_TO' cavactl grad_to Cava_Grad_To_Color '$me')")
    
    out+=("^sep(<i>$GENERATEFROMWP</i>)")
    out+=("<span bgcolor='${w[-3]}'>    </span><span bgcolor='${w[3]}'>    </span>  $LIGHTBG,w2theme cava light;$me")
    out+=("<span bgcolor='${w[3]}'>    </span><span bgcolor='${w[-3]}'>    </span>  $DARKBG,w2theme cava dark;$me")
    out+=("^sep($BARS)")
    out+=("$BAR_WIDTH	[ <b>$BW</b> ],^checkout(barwidth)")
    out2+=("^tag(barwidth)")
    out2+=("^sep($BAR_WIDTH)")
    for i in 1 2 3 4 5 6 8 10 20
    do
    [[ "$BW" == "$i" ]] && out2+=("<big>${ron}</big>   <b>$i</b>,cavactl bar_width $i;$me") || out2+=("<big>${roff}</big>   $i,cavactl bar_width $i;$me")
    done
        
    out+=("$BAR_SPACING 	[ <b>$BS</b> ],^checkout(barspacing)")
    out2+=("^tag(barspacing)")
    out2+=("^sep($BAR_SPACING)")
    for i in 0 1 2 3 4 5 6 8 10
    do
    [[ "$BS" == "$i" ]] && out2+=("<big>${ron}</big>   <b>$i</b>,cavactl bar_spacing $i;$me") || out2+=("<big>${roff}</big>   $i,cavactl bar_spacing $i;$me")
    done
    out+=("^sep($_GENERAL)")
    out+=("$_FRAMERATE	[ <b>$FPS</b> ],^checkout(fps)")
    out2+=("^tag(fps)")
    out2+=("^sep($_FRAMERATE)")
    for i in 144 120 60
    do
    [[ "$FPS" == "$i" ]] && out2+=("<big>${ron}</big>   <b>$i</b>,cavactl framerate $i;$me") || out2+=("<big>${roff}</big>   $i,cavactl framerate $i;$me")
    done
    
    out+=("$_NOISE_RED	[ <b>$NOISE_RED</b> ],^checkout(sens)")
    out2+=("^tag(sens)")
    out2+=("^sep($_NOISE_RED)")
    for i in 90 77 50 25
    do
    [[ "$NOISE_RED" == "$i" ]] && out2+=("<big>${ron}</big>   <b>$i</b>,cavactl noise_reduction $i;$me") || out2+=("<big>${roff}</big>   $i,cavactl noise_reduction $i;$me")
    done
    
        
    out+=("^sep()")
    out+=("<big></big>   $EDITCONF,xdg-open ~/.config/cava/config")
    out+=("<big>󰑓</big>    $_RESETCFG,cavactl resetcfg;$me")
    
    #out+=("^sep()")
    #out+=("󰑓   $RELOAD_COLORS,cavactl reload_colors;$me")
    #out+=("󰑓   $RELOAD,cavactl reload;$me")
    
    out+=("^sep()")
    out+=("<big> </big>   $INFO,cavactl info")
    

### 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"
    TABS=200
    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

[[ "$GR" == "1" ]] && clr=${GR_FROM} || clr=${FG}

cat <<EOF > ${MENU_ITEMS}
@icon,,$((jgtools_padding)),$((jgtools_padding)),270,150,4,left,top,,,${THUMB}
@icon,,$((jgtools_padding+2)),$((jgtools_padding+2)),266,146,4,left,top,,,/usr/share/mabox/img/colorizer-cava.png


@rect,,$((jgtools_padding+4)),$((jgtools_padding + 118)),262,28,0,left,top,#222222 20,#222222 70,
@text,,$((jgtools_padding + 128)),$((jgtools_padding + 118)),120,28,0,left,top,#FFFFFF ,${WINCLR},<span size='10400' font_family='Ubuntu'><b>Cava</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[@]}"

