#!/bin/bash

source "$(dirname $_)/shared.sh" || exit 1

PKGPATH="$(sed -e 's/\./\//g' <<< $PKG)"

if [[ $# -eq 0 ]]; then
	CLASSES="Drug DoseEvent Schedule"
else
	CLASSES="$@"
fi

read -ra DB_VERSION <<< $(grep -o -E 'DB_VERSION = [[:digit:]]+' src/main/java/${PKGPATH}/db/DatabaseHelper.java)

TARGET_DIR=src/main/java/${PKGPATH}/db/v${DB_VERSION[2]}
mkdir -p ${TARGET_DIR}

for c in $CLASSES; do
	f="${TARGET_DIR}/Old$c.java"	
	[[ -e "$f" ]] && die "Refusing to overwrite $f"

	echo ${f}

	echo -e "package $PKG.db.v${DB_VERSION[2]};\n" > ${f}
	echo "@SuppressWarnings({ \"unused\", \"serial\" })" >> ${f}
	run grep @DatabaseTable src/main/java/${PKGPATH}/db/$c.java >> ${f}
	echo "public class Old$c extends Entry" >> ${f}
	echo "{" >> ${f}

	grep @DatabaseField -A1 src/main/java/${PKGPATH}/db/$c.java | sed -E -e 's/^--//' -e 's/useGetSet = true/useGetSet = false/g' >> ${f}

	cat >> ${f} <<EOF
		
	@Override
	public Entry convertToCurrentDatabaseFormat()
	{
		final $c new$c = new $c();
		Entry.copy(new$c, this);
		// TODO some more magic here?
		return new$c;
	}

	@Override
	public boolean equals(Object other) {
		throw new UnsupportedOperationException();
	}

	@Override
	public int hashCode() {
		throw new UnsupportedOperationException();
	}
EOF

	echo "}" >> ${f}
done
