## Authors:
##   Ajrat Makhmutov <rauty@altlinux.org>
##
## Copyright (C) 2024-2026  Basealt LLC
##
## This file is part of alterator-kopidel.
##
## alterator-kopidel 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.
##
## alterator-kopidel 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 alterator-kopidel.
## If not, see <https://www.gnu.org/licenses/>.

if [ -n "${__included_kopidel_progress_bars-}" ]; then
	return 0
fi
readonly __included_kopidel_progress_bars=1

progress_bar_is_drawable() (
	[ -t 1 ] && [ -n "$TERM" ] && [ "$TERM" != dumb ] &&
		[ "$(locale charmap 2>/dev/null)" = UTF-8 ] &&
		tput cols >/dev/null 2>&1
)

repeat_char() (
	printf -v spaces '%*s' "$2" ''
	echo -n "${spaces// /$1}"
)

readonly PLAIN_BAR_LENGTH=10

draw_plain_progress_bar_handler() (
	drawn=0

	while read -r percentage_line; do
		if [[ "$percentage_line" != "step_progress: "* ]]; then
			continue
		fi

		percentage="${percentage_line#step_progress: }"
		marks="$(( percentage * PLAIN_BAR_LENGTH / 100 ))"

		if [ "$marks" -gt "$drawn" ]; then
			drawn="$marks"
			printf '%-*s %3d%%\n' "$PLAIN_BAR_LENGTH" \
				"$(repeat_char '#' "$marks")" "$percentage"
		fi
	done
)

readonly WIDEST_PERCENTAGE_LABEL=' 100%'

draw_progress_bar_handler() (
	yellow_bold_color='\033[1;33m'
	default_color='\033[0m'

	full_block='█'
	left_eighth_blocks=( ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ )

	while read -r percentage_line; do
		if [[ "$percentage_line" != "step_progress: "* ]]; then
			continue
		fi

		percentage="${percentage_line#step_progress: }"
		bar_length="$(( $(tput cols) - ${#WIDEST_PERCENTAGE_LABEL} ))"
		bar_end=" $percentage%"

		if [ "$percentage" -ge 100 ]; then
			bar_main="$(repeat_char "$full_block" "$bar_length")"
		else
			bar_end=" $bar_end"
			(( eighths = bar_length * 8 * percentage / 100 ))
			(( full_blocks_count = eighths / 8 ))
			bar_main="$(repeat_char "$full_block" "$full_blocks_count")"
			bar_main+="${left_eighth_blocks[eighths % 8]}"
			bar_main+="$(repeat_char ' ' "$(( bar_length - full_blocks_count - 1 ))")"
		fi

		echo -e -n "\r$yellow_bold_color$bar_main$default_color$bar_end"
	done
)
