#!/bin/sh
#Ptiming
#Copyright 2011,2012,2013
#Sigmund Berglund - Valåmoen, Norway.

#------------------------------
#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 version 2.

#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. <http://www.gnu.org/licenses/>.
#------------------------------

#gettext
export TEXTDOMAIN=ptiming
export OUTPUT_CHARSET=UTF-8


save(){
	cd $HOME
	echo "$HOME/pTiming.csv" > $WORKDIR/SAVEFILE
	echo pTiming.csv > $WORKDIR/SAVEFILE_NAME

	export savebox='
	<window title="pTiming - '$(gettext 'Save startlist')'" icon-name="ptiming" resizable="false">
	 <vbox>
	  <entry><variable>SAVEFILE</variable><input>cat '$WORKDIR'/SAVEFILE_NAME</input></entry>
	  <chooser>
	   <height>400</height><width>600</width>
	   <variable>CHOOSER</variable>
	   <action>[ -f "$CHOOSER" ] && basename "`echo "$CHOOSER"`" > '$WORKDIR'/SAVEFILE_NAME</action>
	   <action>refresh: SAVEFILE</action>
	  </chooser>
	  <hbox>
	   <button cancel></button>
	   <button can-default="true" has-default="true" use-stock="true"><input file icon="gtk-save"></input><label>'$(gettext 'Save startlist')'</label><action type="exit">save</action></button>
	  </hbox>
	 </vbox>
	</window>'

	I=$IFS; IFS=""
	for STATEMENTS in  $(gtkdialog -p savebox); do
		eval $STATEMENTS
	done
	IFS=$I

	if [ "$EXIT" = "save" ]; then
		CHOOSER="`dirname "$CHOOSER"`" #we want to define the dir we're standing in, not the autoselected one.
		SAVEFILE="`echo "$CHOOSER"/"$SAVEFILE".csv | sed -e "s%\.csv.csv%.csv%g"`" #remove double extension if exist.
		#check if exist
		if [ -f "${SAVEFILE}" ]; then #already exist
			IMG=warning; FRAME=Warning; TXT1="<b>File already exist</b>"; TXT2="Overwrite?"
			. $APPDIR/box_yesno
			[ $EXIT = yes ] && mv $WORKDIR/pTiming.csv "$SAVEFILE"
		else
			mv $WORKDIR/pTiming.csv "$SAVEFILE"
		fi
	fi
}

open(){
	export openbox='
	<window title="pTiming - '$(gettext 'Open startlist')'" icon-name="ptiming">
	 <vbox>
	   <chooser>
		<height>400</height><width>600</width>
		<variable>CHOOSER</variable>
	   </chooser>
	  <hbox>
	   <button cancel></button>
	   <button can-default="true" has-default="true" use-stock="true">
	    <input file icon="gtk-open"></input>
	    <label>'$(gettext 'Open startlist')'</label>
	    <action>tac "$CHOOSER" | sed '"'"'s/","/|/g'"'"' | sed "s/^\"//g" | sed "s/\"$//g" > '$WORKDIR'/startlist</action>
	    <action type="exit">open</action>
	    <action>refresh:STARTLIST</action>
	   </button>
	  </hbox>
	 </vbox>
	</window>'

	I=$IFS; IFS=""
	for STATEMENTS in  $(gtkdialog -p openbox); do
		eval $STATEMENTS
	done
	IFS=$I
}

edit(){
	[ ! "$STARTLIST" ] && exit
	#read info from list
	EDIT_NR=`grep "^$STARTLIST|" $WORKDIR/startlist | cut -d'|' -f1`
	NR=$EDIT_NR #check if changed after 'apply'
	EDIT_TIME=`grep "^$STARTLIST|" $WORKDIR/startlist | cut -d'|' -f2`
	EDIT_NAME=`grep "^$STARTLIST|" $WORKDIR/startlist | cut -d'|' -f3`
	EDIT_ORG=`grep "^$STARTLIST|" $WORKDIR/startlist | cut -d'|' -f4`
	EDIT_CLASS=`grep "^$STARTLIST|" $WORKDIR/startlist | cut -d'|' -f5`
	#geometry
	XWININFO=`xwininfo -stats -name $(gettext 'Competitors')`
	WIDTH=`echo "$XWININFO" | grep 'Width:' | awk '{print $2}'`
	export X=`echo "$XWININFO" | grep 'Absolute upper-left X' | awk '{print $4}'` #export to use in <progressbar> loop
	export Y=$(((`getcurpos | awk '{print $2}'`)-20))
	#---
	export Competitors_edit='
	<window height-request="50" width-request="'$WIDTH'" skip-taskbar-hint="true" decorated="false">
	 <vbox>
	  <hbox width-request="1">
	   <progressbar width-request="1" height-request="1" >
	    <input>LOOP2=true; while [ $LOOP2 = true ]; do MOUSEX=`getcurpos | awk '"'"'{print $1}'"'"'`; MOUSEY=`getcurpos | awk '"'"'{print $2}'"'"'`; if [ $MOUSEX -lt $X ] || [ $MOUSEX -gt '$(($X+$WIDTH))' ] || [ $MOUSEY -lt $Y ] || [ $MOUSEY -gt '$(($Y+50))' ]; then LOOP2=false; echo; echo 100; fi; sleep 1; done</input>
	    <action>EXIT:exit</action>
	   </progressbar>
	  </hbox>
	  <hbox tooltip-text="'$(gettext 'Apply changes by pressing ENTER')'">
	   <entry name="edit" width-request="35"><input>echo '$EDIT_NR'</input><variable>EDIT_NR</variable><action signal="activate">EXIT:apply</action></entry>
	   <entry name="edit" width-request="80"><input>echo '$EDIT_TIME'</input><variable>EDIT_TIME</variable><action signal="activate">EXIT:apply</action></entry>
	   <entry name="edit" width-request="130"><input>echo "'$EDIT_NAME'"</input><variable>EDIT_NAME</variable><action signal="activate">EXIT:apply</action></entry>
	   <entry name="edit" width-request="115"><input>echo "'$EDIT_ORG'"</input><variable>EDIT_ORG</variable><action signal="activate">EXIT:apply</action></entry>
	   <entry name="edit" width-request="85"><input>echo "'$EDIT_CLASS'"</input><variable>EDIT_CLASS</variable><action signal="activate">EXIT:apply</action></entry>
	   <text width-request="'$(($WIDTH-565))'"><label>""</label></text>
	   <button visible="false" can-default="true" has-default="true"><action>EXIT:apply</action></button>
	   <vbox homogeneous="true"><button height-request="30" tooltip-text="'$(gettext 'Delete competitor')'"><input file stock="gtk-delete"></input><action>EXIT:delete</action></button></vbox>
	  </hbox>
	 </vbox>
	 <action signal="focus-out-event">EXIT:exit</action>
	</window>'
	gtkdialog -p Competitors_edit -G +"$X"+"$Y" > $WORKDIR/returnvalues
	chmod 722 $WORKDIR/returnvalues
	. $WORKDIR/returnvalues
	case $EXIT in
		delete)
			grep -v "^$STARTLIST" $WORKDIR/startlist > $WORKDIR/tmp
			mv -f $WORKDIR/tmp $WORKDIR/startlist
			;;
		apply)
			if [ $EDIT_NR != $NR ] && [ "`grep "^$EDIT_NR" $WORKDIR/startlist`" ]; then 
				TXT1="Nr already exist"; . $APPDIR/box_ok
			else
				HOUR=`echo $EDIT_TIME | cut -d: -f1`
				MIN=`echo $EDIT_TIME | cut -d: -f2`
				SEC=`echo $EDIT_TIME | cut -d: -f3`
				EDIT_SEC=`echo "($HOUR*3600)+($MIN*60)+$SEC" | bc`
				grep -B 10000 "^$STARTLIST" $WORKDIR/startlist | grep -v "^$STARTLIST" > $WORKDIR/tmp
				grep -A 10000 "^$STARTLIST" $WORKDIR/startlist | grep -v "^$STARTLIST" > $WORKDIR/tmp1
				echo "$EDIT_NR|$EDIT_TIME|$EDIT_NAME|$EDIT_ORG|$EDIT_CLASS||$EDIT_SEC" >> $WORKDIR/tmp
				cat $WORKDIR/tmp1 >> $WORKDIR/tmp
				mv -f $WORKDIR/tmp $WORKDIR/startlist
			fi
			;;
	esac
}

generate (){
	cut -d '|' -f5 $WORKDIR/startlist | grep -v "^$" | sort -u > $WORKDIR/classes #find classes
	#build <tree> input
	echo -n > $WORKDIR/class_starttime
	COUNT=0
	while read CLASS; do
		PNR=`grep -c "|$CLASS|" $WORKDIR/startlist`
		SEC=$COUNT
		COUNT=$((($COUNT)+(($PNR+$LATE_REGISTRATION)*$START_INTERVAL))) #total length of starting procedure for given class
		STARTTIME=`printf "%02d:%02d:%02d" $((SEC/3600)) $((SEC%3600/60)) $((SEC%60))`
		echo "$CLASS|$PNR|$STARTTIME||$SEC" >> $WORKDIR/class_starttime
	done < $WORKDIR/classes
	#---
	export generator='
	<window title="'$(gettext 'Shuffle_Competitors')'" icon-name="ptiming" height-request="300">
	 <vbox>
	  <frame>
	   <hbox>
	    <text><label>'$(gettext 'First Start NR')'</label></text>
	    <hbox><entry width-request="40"><variable>GENERATOR_NR</variable><default>1</default></entry></hbox>
	   </hbox>
	   <hbox>
	    <text><label>'$(gettext 'Delay between Competitors in class (seconds)')'</label></text>
        <hbox><entry width-request="40"><variable>START_INTERVAL</variable><default>'$START_INTERVAL'</default></entry></hbox>
	   </hbox>
	   <tree hover_selection="true" headers-clickable="false">
	    <label>'$(gettext 'Class')'|'$(gettext 'Competitors')'|'$(gettext 'First starttime')'|                                                                                  |</label>
	    <variable>CLASS_STARTTIME</variable>
	    <input>cat '$WORKDIR'/class_starttime</input>
		<action signal="button-press-event">generate_edit</action>
		<action signal="button-press-event">refresh:CLASS_STARTTIME</action>
	   </tree>
	  </frame>
	  <hbox>
	   <button cancel></button>
	   <button can-default="true" has-default="true" use-stock="true">
	    <input file icon="gtk-execute"></input>
	    <label>'$(gettext 'Execute')'</label>
	    <action type="exit">generate</action>
	   </button>
	  </hbox>
	 </vbox>
	</window>'

	I=$IFS; IFS=""
	for STATEMENTS in  $(gtkdialog -p generator); do
		eval $STATEMENTS
	done
	IFS=$I
	
	if [ $EXIT = generate ]; then
		echo -n > $WORKDIR/startlist_generated
		while read CLASS; do
			#set class starttime
			SEC=`grep "^$CLASS|" $WORKDIR/class_starttime | cut -d'|' -f5`
			#ramdonize Competitors in class
			grep "|$CLASS|" $WORKDIR/startlist | sort -Ru > $WORKDIR/tmp2
			#set new time/nr
			while read P; do
				NAME=`echo "$P" | cut -d'|' -f3`
				ORG=`echo "$P" | cut -d'|' -f4`
				[ ! "$NAME" ] && continue
				TIME=`printf "%02d:%02d:%02d" $((SEC/3600)) $((SEC%3600/60)) $((SEC%60))`
				echo "$GENERATOR_NR|$TIME|$NAME|$ORG|$CLASS||$SEC" >> $WORKDIR/startlist_generated
				GENERATOR_NR=$(($GENERATOR_NR+1))
				SEC=$(($SEC+$START_INTERVAL))
			done < $WORKDIR/tmp2
		done < $WORKDIR/classes
		tac $WORKDIR/startlist_generated > $WORKDIR/startlist
	fi
}

generate_edit(){
	[ ! "$CLASS_STARTTIME" ] && exit
	#read info from list
	GEN_CLASS=`grep "^$CLASS_STARTTIME|" $WORKDIR/class_starttime | cut -d'|' -f1`
	GEN_NR=`grep "^$CLASS_STARTTIME|" $WORKDIR/class_starttime | cut -d'|' -f2`
	GEN_TIME=`grep "^$CLASS_STARTTIME|" $WORKDIR/class_starttime | cut -d'|' -f3`
	#geometry
	XWININFO=`xwininfo -stats -name $(gettext 'Shuffle_Competitors')`
	WIDTH=`echo "$XWININFO" | grep 'Width:' | awk '{print $2}'`
	export X=`echo "$XWININFO" | grep 'Absolute upper-left X' | awk '{print $4}'` #export to use in <progressbar> loop
	export Y=$(((`getcurpos | awk '{print $2}'`)-20))
	#---
	export gen_edit='
	<window height-request="50" width-request="'$WIDTH'" skip-taskbar-hint="true" decorated="false">
	 <vbox>
	  <hbox width-request="1">
	   <progressbar width-request="1" height-request="1" >
	    <input>LOOP2=true; while [ $LOOP2 = true ]; do MOUSEX=`getcurpos | awk '"'"'{print $1}'"'"'`; MOUSEY=`getcurpos | awk '"'"'{print $2}'"'"'`; if [ $MOUSEX -lt $X ] || [ $MOUSEX -gt '$(($X+$WIDTH))' ] || [ $MOUSEY -lt $Y ] || [ $MOUSEY -gt '$(($Y+50))' ]; then LOOP2=false; echo; echo 100; fi; sleep 1; done</input>
	    <action>EXIT:exit</action>
	   </progressbar>
	  </hbox>
	  <hbox>
	   <entry width-request="180"><input>echo '$GEN_CLASS'</input><visible>disabled</visible></entry>
	   <entry name="edit" width-request="120" activates-default="true" tooltip-text="'$(gettext 'Apply changes by pressing ENTER')'"><input>echo "'$GEN_TIME'"</input><variable>GEN_TIME</variable></entry>
	   <text width-request="'$(($WIDTH-300))'"><label>""</label></text>
	   <button visible="false" can-default="true" has-default="true"><action>EXIT:apply</action></button>
	  </hbox>
	 </vbox>
	 <action signal="focus-out-event">EXIT:exit</action>
	</window>'
	gtkdialog -p gen_edit -G +"$X"+"$Y" > $WORKDIR/returnvalues
	chmod 722 $WORKDIR/returnvalues
	. $WORKDIR/returnvalues
	case $EXIT in
		apply)
			HOUR=`echo $GEN_TIME | cut -d: -f1`
			MIN=`echo $GEN_TIME | cut -d: -f2`
			SEC=`echo $GEN_TIME | cut -d: -f3`
			GEN_SEC=`echo "($HOUR*3600)+($MIN*60)+$SEC" | bc`
			grep -B 10000 "^$CLASS_STARTTIME" $WORKDIR/class_starttime | grep -v "^$CLASS_STARTTIME" > $WORKDIR/tmp
			grep -A 10000 "^$CLASS_STARTTIME" $WORKDIR/class_starttime | grep -v "^$CLASS_STARTTIME" > $WORKDIR/tmp1
			echo "$GEN_CLASS|$GEN_NR|$GEN_TIME||$GEN_SEC" >> $WORKDIR/tmp
			cat $WORKDIR/tmp1 >> $WORKDIR/tmp
			mv -f $WORKDIR/tmp $WORKDIR/class_starttime
			;;
	esac
}

export -f save open edit generate generate_edit
	
export Competitors='
<window title="'$(gettext 'Competitors')'" icon-name="ptiming" window_position="2" height-request="500" width-request="570">
 <vbox>
  <menubar>
   <menu>
    <menuitem stock="gtk-new" label="'$(gettext 'New startlist')'">
     <action>echo -n > '$WORKDIR'/startlist</action>
     <action>refresh:STARTLIST</action>
    </menuitem>
    <menuitem stock="gtk-open" label="'$(gettext 'Open startlist')'">
     <action>open</action>
     <action>refresh:STARTLIST</action>
    </menuitem>
    <menuitem stock="gtk-save" label="'$(gettext 'Save startlist')'">
     <action>tac '$WORKDIR'/startlist | sed '"'"'s/|/","/g'"'"' | sed "s/^/\"/g" | sed "s/$/\"/g" > '$WORKDIR'/pTiming.csv</action>
     <action>save</action>
    </menuitem>
    <separator></separator>
    <menuitem stock="gtk-edit" label="'$(gettext 'Export startlist')'">
     <action>cp '$WORKDIR'/startlist '$WORKDIR'/tmp; echo -e "\n'$(gettext 'ID')'|'$(gettext 'StartTime')'|'$(gettext 'Name')'|'$(gettext 'Organization')'|'$(gettext 'Class')'\n" >> '$WORKDIR'/tmp; tac '$WORKDIR'/tmp | cut -d"|" -f1-5 | sed '"'"'s/|/","/g'"'"' | sed "s/^/\"/g" | sed "s/$/\"/g" > '$WORKDIR'/pTiming.csv</action>
     <action>defaultspreadsheet '$WORKDIR'/pTiming.csv &</action>
    </menuitem>
    <separator></separator>
    <menuitem stock="gtk-quit" label="'$(gettext 'Close')'"><action>exit:EXIT</action></menuitem>
     <label>'$(gettext 'File')'</label>
    </menu>
   </menubar>
   <vbox>
   <frame '$(gettext 'Registration')'>
    <hbox>
     <text><label>'$(gettext 'Delay between Competitors (seconds)')'</label></text>
     <hbox><entry width-request="40"><variable>INCREASE</variable><default>'$START_INTERVAL'</default></entry></hbox>
    </hbox>
	<hbox>
	 <entry width-request="35" activates-default="true"><variable>ADD_NR</variable><input>echo $((ADD_NR+1))</input></entry>
	 <entry width-request="70" activates-default="true"><variable>ADD_STARTTIME</variable><default>00:02:00</default><input>HOUR=`echo $ADD_STARTTIME | cut -d: -f1`; MIN=`echo $ADD_STARTTIME | cut -d: -f2`; SEC=`echo $ADD_STARTTIME | cut -d: -f3`; TMP=$(((`echo "($HOUR*3600)+($MIN*60)+$SEC" | bc`)+$INCREASE)); printf "%02d:%02d:%02d" $(($TMP/3600)) $(($TMP%3600/60)) $(($TMP%60))</input></entry>
	 <entry width-request="135" activates-default="true"><variable>ADD_NAME</variable><default>Name</default></entry>
	 <entry width-request="130" activates-default="true"><variable>ADD_ORG</variable><default>Organization</default></entry>
	 <entry width-request="80" activates-default="true"><variable>ADD_CLASS</variable><default>Class</default></entry>
	 <button can-default="true" has-default="true">
	  <input file stock="gtk-add"></input>
	  <action>if [ ! "`grep "^$ADD_NR" '$WORKDIR'/startlist`" ]; then HOUR=`echo $ADD_STARTTIME | cut -d: -f1`; MIN=`echo $ADD_STARTTIME | cut -d: -f2`; SEC=`echo $ADD_STARTTIME | cut -d: -f3`; ADD_SEC=`echo "($HOUR*3600)+($MIN*60)+$SEC" | bc`; echo "$ADD_NR|$ADD_STARTTIME|$ADD_NAME|$ADD_ORG|$ADD_CLASS||$ADD_SEC" >> '$WORKDIR'/startlist; else TXT1="ID _${ADD_NR}_ already exist"; . '$APPDIR'/box_ok; fi</action>
	  <action>refresh:STARTLIST</action>
	  <action>refresh:ADD_NR</action>
	  <action>refresh:ADD_STARTTIME</action>
	 </button>
	</hbox>
   </frame>
   </vbox>
   <tree hover_selection="true" sort-function="1">
    <variable>STARTLIST</variable>
    <label>'$(gettext 'ID')'|'$(gettext 'StartTime')'|'$(gettext 'Name')'                    |'$(gettext 'Organization')'       |'$(gettext 'Class')'           |                                                  |</label> 
    <input>tac '$WORKDIR'/startlist</input>
    <action signal="button-press-event">edit</action>
    <action signal="button-press-event">refresh:STARTLIST</action>
   </tree>
   <vbox>
    <hbox>
     <button>
      <input file stock="gtk-execute"></input>
      <label>'$(gettext 'Shuffle Competitors')'</label>
      <action>generate</action>
      <action>refresh:STARTLIST</action>
     </button>
     <button ok></button>
    </hbox>
  </vbox>
 </vbox>
</window>'

gtkdialog -p Competitors
