#!/bin/bash

if test "$1" = "--help" && test "$2" = "" ; then
	cat << EOF
param 1 : name of the fake datas json file to convert
(param 2 : name of the repertorie with all C# fake datas files)
EOF
	exit 0
fi

if test $# -lt 1 ; then
	echo "error : param require" >&2
	exit 1
fi

countS=$( echo $1 | tr "/" "\n" | wc -l )
if test $countS -gt 1 ; then
	name=$( echo $1 | cut -d '/' -f $(( $countS )) )
fi
countP=$( echo $name | tr "." "\n" | wc -l )
if test $countP -gt 1 ; then
	name=$( echo $name | cut -d '.' -f -$(( $countP - 1 )))
fi
if test "$2" != "" ; then
	target=$( echo "$2/$name.cs" )
else
	target=$( echo "$name.cs" )
fi

if test "$2" != "" ; then
	if ! ls | egrep -q "^$2$" ; then
		mkdir -p $2
	fi
fi

nom=$( echo $1 | cut -d "-" -f 2 | cut -d '.' -f 1 | sed 's/ies$/ys/' | sed 's/s$//' )
class=$( echo "$nom Entity" | tr -d ' ' )
fic=$( find ../.. -type f -name "*.cs" | xargs egrep "class $class\b" | cut -d ':' -f 1 )
namespaceClass=$( cat $fic | grep "namespace" | cut -d ' ' -f 2 )

# set -x

echo -e "using $namespaceClass;\n" > $target
cat $1 | while read line ; do
	if echo "$line" | egrep -q "^[[:space:]]*\"[[:alnum:]]+\"" ; then
		afficher=$( echo $line | sed "s/^[[:space:]]*\"/\t\t\t/" | sed "s/\"[[:space:]]*:/ =/" )
	
	elif echo "$line" | egrep -q "^[[:space:]]*{$" ; then
		afficher="\t\tnew $class\n\t\t{"
	elif echo "$line" | egrep -q "^[[:space:]]*\[$" ; then
		afficher="public static class $( echo $name | tr -d '-' )\n{\
			\n\tpublic static IEnumerable<$class> datas = new List<$class>\n\t{"
	elif echo "$line" | egrep -q "^[[:space:]]*}" ; then
		if echo "$line" | grep -q "," ; then
			afficher="\t\t},"
		else
			afficher="\t\t}\n\t} ;\n}"
		fi
	fi
	echo -e "$afficher" >> $target
done