
# License GNU GPLv3
# Copyright (C) 2019 step
# Part of checksum script

# Usage:
# awk -v SEP_VALUE="@@" \
# -v CCOL_NAME="$(gettext "⨯|checksum|file name|hash|serial|file path")" \
# -v FEAT_NAME="$(gettext "show progress dialog")" \
# -v HASH="$sel_hash" -v CCOL="$sel_ccol" -v FEAT="$sel_feat"

# On entering this script, stdin lines (in context "hash" or "ccol" or "feat") hold
# configuration defaults, whereas HASH, CCOL and FEAT hold the current values that
# update the defaults.
# This script combines all values and outputs the result in yad --list input format.

# Skip white lines
/^[[:space:]]*$/ { next }

# Change context
/^hash|ccol|feat$/ { context = $0; next }

BEGIN {
	print "on\n" SEP_VALUE "\ncontext hash"
}

"hash" == context { # {{{1
# Output: Name"|"Command" "Name" "State"\n"

	# Update defaults
	if(index("/"HASH"/", "/"$1"/")) { $3 = "on" }

	# Reverse columns for yad
	print $3"\n" $2"\n" $1
}

"ccol" == context { # {{{1
# Output (all on one line): Digit","Digit...

	# Append yad --list separator line
	print "on\n" SEP_VALUE "\ncontext ccol"
	# Unpack copy-column names
	nK = split(CCOL_NAME, K, /\|/)
	# Normalize format
	gsub("/",  ",", CCOL)
	gsub(/,+/, ",", CCOL)
	gsub(/,+/, ",")
	delete V
	# Merge values
	for(i = 1; i <= nK; i++) {
		# Initialize from default configuration
		V[i] = index(","$0",", ","i",") ? "on" : "off"
		# Update from current value
		if(CCOL) { V[i] = index(","CCOL",", ","i",") ? "on" : "off" }

		print V[i]"\n" K[i]"\n" i
	}
}

"feat" == context { # {{{1
# Output (all on one line) : "1"Flag",2"Flag...",nK"Flag, where [1..nK] are all assigned feature numbers.
# An input list element can be N! (hide), N+ (check) or N- (uncheck).
# Any missing element M default to M-. On multiples of the same element, the last occurrence wins.

	# Append yad --list separator line
	print "on\n" SEP_VALUE "\ncontext feat"
	# Unpack feature names - [1..nK] is the range of all assigned features
	nK = split(FEAT_NAME, K, /\|/)
	# Normalize format
	gsub("/",  ",", FEAT)
	gsub(/,+/, ",", FEAT)
	gsub(/,+/, ",")
	# Deal with multiple occurrences - the last one wins
	nF = split($0, F, /,/)
	delete Z
	for(i = 1; i <= nF; i++) { Z[0 + substr(F[i], 1, 1)] = F[i] }
	# Merge values
	nF = split($0, F, /,/)
	delete V
	for(i = 1; i <= nK; i++) {
		# Initialize from default configuration
		V[i] = index(Z[i], "!") ? "hide" : ( index(Z[i], "-") ? "off" : "on" )
		# Update from current value (
		if(FEAT) { V[i] = index(","FEAT",", ","i"!,") ? "hide" : ( index(","FEAT",", ","i"-,") ? "off" : "on" ) }

		if ("hide" == V[i]) {
			# Hide the row by making yad diplay it as a separator line.
			# Yad does output checked separator lines as if they were regular values
			print "ON\n" SEP_VALUE "\n" i"!"  # so we are able to output "!"
		} else {
			print V[i]"\n" K[i]"\n" i
		}
	}
}
