#!/bin/bash
shopt -s extglob

hc() {
    # t="$EPOCHREALTIME"
    herbstclient "$@"
    # t2="$EPOCHREALTIME"
    # echo "hc: $( bc<<<"$t2 - $t")" >&2
}
panel_height=18
# bgcolor=$(hc get frame_border_normal_color)
# selbg=$(hc get window_border_active_color)
# selfg='#282828'
# fg='#fbf1c7'
# bgcolor='#282828'
# selsecbg='#ebdbb2'


. "$(dirname "$0")/colors.sh"

col_bg_pri_sel=${colors[active]}
col_fg_pri_sel=${colors[dark0]}

col_bg_sec_sel=${colors[dark3]}
col_fg_sec_sel=${colors[light1]}

col_bg=${colors[dark0]}
col_fg=${colors[light0]}

col_fg_sec=${colors[light4]}

col_bg_urg=${colors[urgent]}

monitors=(  )

i=0
while read -r _ resolution
do
    monitors[$i]="$(herbstclient list_monitors | grep "$resolution" | cut -d":" -f1)"
    i=$((i+1))
done < <(xrandr| awk '/ connected/ { FS=" " ; $0=$0 ; if ($3 == "primary") { res=$4 } else {res=$3} ; FS="+" ; $0=$0 ; print $2" "res }' | sort -n)

first_loop=1

notify() {
    if [[ "$first_loop" != 1 ]]
    then
        #twmnc "$@"
        notify-send "$@"
    fi
}

# so it bootstraps...
( sleep 0.5; hc emit_hook volume ) &

hc --idle | {
    for monitor in "${monitors[@]}" ; do
        tags[$monitor]="$(hc tag_status "$monitor")"
    done
    date="%{T2}%{T-} $(date "+%H:%M%{F${colors[light4]}, %Y-%m-%{F-}%d")"
    windowtitle=""
    #count-mails;
    #charge=$(battery | awk '{print $2}')
    while true ; do

        ### prepare by monitor tags displaying
        for monitor in "${monitors[@]}" ; do
            output_tags[$monitor]="%{A4:herbstclient use_index +1 --skip-visible:}%{A5:herbstclient use_index -1 --skip-visible:}"
            for i in ${tags[$monitor]} ; do
                case ${i:0:1} in
                    '#'|'+')
                        output_tags[$monitor]="${output_tags[$monitor]}%{F$col_fg_pri_sel}%{B$col_bg_pri_sel}"
                        ;;
                    #'+')
                        #output_tags[$monitor]="${output_tags[$monitor]}%{B#3c7693}%{F#141414}"
                        #;;
                    ':')
                        output_tags[$monitor]="${output_tags[$monitor]}%{B-}%{F-}"
                        ;;
                    '!')
                        output_tags[$monitor]="${output_tags[$monitor]}%{B${col_bg_urg}}%{F-}"
                        ;;
                    '-'|'%')
                        output_tags[$monitor]="${output_tags[$monitor]}%{B${col_bg_sec_sel}%{F${col_fg_sec_sel}}"
                        ;;
                    *)
                        output_tags[$monitor]="${output_tags[$monitor]}%{B-}%{F${col_fg_sec}}"
                        ;;
                esac

#                output_tags[$monitor]="${output_tags[$monitor]}%{A:herbstclient use_index $((${i:1} - 1 )):} ${i:1} %{A}"
                output_tags[$monitor]="${output_tags[$monitor]}%{A1:herbstclient use ${i:1}:} ${i:1} %{A}%{B-}%{F-}"
            done
            output_tags[$monitor]="${output_tags[$monitor]}%{A}%{A}"
        done

        #bordercolor="#26221C"
        separator="%{B-}%{F-}| "
        #separator="%{B$selbg} %{B-}%{F-}"
        #right=
        #for st in playing volume wifi temperature load date
        #do
            #data="$(eval $st)"
            #[[ -n "$data" ]] && right="$right $separator $data"
        #done

        ### All drawing happens here
#        echo -n "%{T5}" # set font
        res=
        for m in "${!monitors[@]}" ; do
            monitor=${monitors[$m]}

            ### set monitor
            res+="%{S$m}"
            #echo -en "%{S$((${#monitors[@]} - monitor))}"
            ### print the left
            res+="%{l}${output_tags[$monitor]}$separator${windowtitle:0:150}"
            ### center
            #echo -n "%{c}%{U${colors[bright_orange]}}${windowtitle:0:150}%{U-}"
            ### print the right
            res+="%{r}$alerts$memory$df$playing$volume$wifi$network$temperature$load $separator$date $separator%{U#f2f229}$charge%{U-}$separator"
            #echo -en "%{r}$right $separator %{U#f2f229}$charge%{U-} $separator"
        done

        ### end the output
        echo -e "$res"

        ### Data handling ###
        # This part handles the events generated in the event loop, and sets
        # internal variables based on them. The event and its arguments are
        # read into the array cmd, then action is taken depending on the event
        # name.
        # "Special" events (quit_panel/togglehidepanel/reload) are also handled
        # here.

        # wait for next event
        IFS=$'\t' read -ra cmd || break
        #for z in ${cmd[@]}
        #do
        #echo -n "'$z' " >&2
        #done
        #echo >&2
        # find out event origin
        case "${cmd[0]}" in
            tag*)
                #echo "resetting tags" >&2
                for monitor in "${monitors[@]}" ; do
                    tags[$monitor]="$(hc tag_status "$monitor")"
                done
                ;;
            date)
                #echo "resetting date" >&2
                date="%{T2}%{T-} $(date "+%H:%M%%{F${colors[light4]}}, %Y-%m-%%{F-}%d")"
                ;;
            quit_panel)
                exit
                ;;
            reload)
                exit
                ;;
            load)
                load=" ${cmd[*]:1}"
                ;;
            focus_changed|window_title_changed)
                windowtitle="${cmd[*]:2}"
                windowtitle="${windowtitle/\\n/ ; }"
                ;;
            player)
                # declare -A player_status
                if [[ "${cmd[1]}" = cmus ]] || [[ "${cmd[1]}" = mpd ]]
                then
                    play_line=" ${cmd[3]:0:20}/${cmd[4]:0:20}"
                    [[ -n ${cmd[5]} ]] && play_line="$play_line: ${cmd[5]:0:20}"
                    play_sym=
                    case "${cmd[2]}" in
                        off|Stopped)
                            play_line=
                            ;;
                        Paused)
                            play_sym=
                            ;;
                        *)
                            play_sym="%{T2}%{T-}"
                            ;;
                    esac
                    #playing="$play_sym$play_line"
                    playing="$play_sym"
                    [[ -n "$playing" ]] && playing+=" $separator"
                fi

                # [[ "${player_status[${cmd[1]}]}" != "${cmd[2]}" ]] &&
                # notify "Player: ${cmd[1]}" "${cmd[2]}"
                # player_status[${cmd[1]}]="${cmd[2]}"
                ;;

            alerts)
                alerts=" ${cmd[1]} $separator"
                ;;

            battery)
                #echo "battery" >&2
                batt_perc="${cmd[1]}"
                { [ "$batt_perc" -ge 95 ] && batt_sym= ; } ||
                { [ "$batt_perc" -ge 75 ] && batt_sym= ; } ||
                { [ "$batt_perc" -ge 50 ] && batt_sym= ; } ||
                { [ "$batt_perc" -ge 25 ] && batt_sym= ; } ||  batt_sym=

                old_ac="$ac"
                case ${cmd[2]} in
                    charging)
                        batt_sym="%{F#00aa00}$batt_sym%{F-}"
                        ac="+"
                        [[ "$old_ac" != "$ac" ]] && notify "Power" "Battery charging"
                        ;;
                    discharging)
                        ac="-"
                        batt_sym="%{F#ffdb00}$batt_sym%{F-}"
                        [[ "$old_ac" != "$ac" ]] && notify "Power" "Battery discharging"
                        ;;
                    idle)
                        ac="="
                        [[ "$old_ac" != "$ac" ]] && notify "Power" "Fully charged"
                        ;;
                esac

                charge="$batt_sym ${batt_perc}%%"

                [ "$batt_perc" -le 15 ] && [ "$ac" != '+' ] && notify -u critical "Power" "Battery has only ${batt_perc}%"
                ;;
            df)
                df=""
                for f in "${cmd[@]:1}"
                do
                    IFS=: read -r name perc <<<"$f"
                    [[ "${perc%%%}" -lt 80 ]] && continue
                    df+="  $name $perc"
                done
                [[ -n "$df" ]] && df+=" $separator"
                ;;
            memory)
                if (( (cmd[2]*100) / cmd[1] > 50 ))
                then
                    memory=" $(LC_ALL=C numfmt --from-unit=Ki --to=iec --format %.2f "${cmd[2]}") $separator"
                else
                    memory=""
                fi
                ;;
            temperature)
                temperature=" ${cmd[1]}°C $separator"
                ;;
            wifi)
                _wifi_net="${cmd[1]}"
                if [[ -n "$_wifi_net" ]]
                then
                    _wifi_sym=
                else
                    _wifi_sym=
                fi
                wifi="$(xargs <<<"$_wifi_sym $_wifi_net $separator")"
                ;;

            network)
                _net_status="${cmd[1]}"
                if [[ "$_net_status" == 'UP' ]]
                then
                    network="󰛳 $(xargs <<<"${cmd[2]}") $separator"
                else
                    network=
                fi
                ;;

            volume)
                sleep 0.1

                mute="$(pactl get-sink-mute "$(pactl get-default-sink)" | awk '{print $2}')"

                if [[ "$mute" == yes ]]
                then
                    volume=" $separator"
                else
                    volume=" ${cmd[1]} $separator"
                fi
                ;;
        esac
        first_loop=0
    done

} | lemonbar -f "Hack-10" -f "Symbols Nerd Font Mono" -f "Noto Color Emoji-10" -a30 -B "$col_bg" -F "$col_fg" -u 1 | sh
#} | lemonbar -f "DejaVu Sans-9" -f "Font Awesome-9" -f "Symbols Nerd Font-9"
#} | tee >(lemonbar -f "DejaViu Sans-9" -f "Font Awesome-9" )

systemctl stop --user "hlwm.target"
