#!/bin/bash

#-----------------------------------  colors ----------------------------------#
black='\E[30;47m'
red='\E[31;47m'
green='\E[32;47m'
yellow='\E[33;47m'
blue='\E[34;47m'
magenta='\E[35;47m'
cyan='\E[36;47m'
white='\E[37;47m'

#-------- from : http://www.faqs.org/docs/abs/HTML/colorizing.html -----------#
###  
cecho ()                      # Color-echo.
                              # Argument $1 = message
                              # Argument $2 = color
 {
	 local default_msg="No message passed."
				      # Doesn't really need to be a local variable.
	 
	 message=${1:-$default_msg}   # Defaults to default message.
	 color=${2:-$black}           # Defaults to black, if not specified.

	   echo -en "$color"
	   echo -n "$message"
	   tput sgr0	 
	 
	   return
}  
#------------------------------------------------------------------------------#

tags=` wmiir read /tags` 			#list of tags
nl=`wmiir read /tags | awk 'END { print NR }'` 	#number of tags


########## populate tagar ##################
i=1
for ctag in $tags 
do
	tagar[$i]=$ctag
        #echo -n "  $i.$ctag "
	i=`expr $i + 1`
done

####### get tags for selected client #######
seltags=`wmiir read /view/sel/sel/tags | sed -e "s/+/ /g"` 

###### populate choicear ###################
for cseltag in  $seltags
do
	#echo $cseltag
	for i in `seq 1 $nl` 
	do
		if [ "$cseltag" = "${tagar[$i]}" ]; then
			choicear[$i]=1
		fi
		
	done
done
while (true) do
	clear
	for i in `seq 1 $nl`; 
	do
		if [ "${choicear[$i]}" = "1" ]; then
		
		  #     echo -ne $red"$i.[${tagar[$i]}] "'\033[0m'
	    	cecho "$i.[${tagar[$i]}] " $red
		else
		     # echo -n "$i. ${tagar[$i]}  "
		      cecho "$i. ${tagar[$i]}  " $blue
		fi
		#tput sgr0
	done
	echo; echo
	cecho  "########## KEYS ############" $black; echo
	cecho  "# 1..9 toggle tag          #" $black; echo
#	cecho  "# x    exit without saving #" $black; echo
	cecho  "# q    save and exit       #" $black; echo
	cecho  "############################" $black; echo
	read -s -n1 ch
	case "$ch" in 
	[1-9])
		if [ "${choicear[$ch]}" = "1" ]; then
			choicear[$ch]=0
		else
			choicear[$ch]=1
		fi;;
	x)
		clear;exit;;
	q) 
		#construct tags string
		for i in `seq 1 $nl`
		do
			if [ "${choicear[$i]}" = "1" ]; then
				if [ "$new_tags" = "" ]; then
					new_tags=${tagar[$i]}
			   	else			
					new_tags=$new_tags+${tagar[$i]}
				fi
			fi
		done
		echo -n "The new tags for the selected client would be: "
		echo $new_tags
		
		exit;;
	esac
done

