#!/bin/bash
source $HOME/.gamerc

ITEM_ID_LISTS=$@

ITEM_ID_SQL_PARAMS=""
for item_id in ${ITEM_ID_LISTS}; do
	if [[ $item_id == *"-"* ]]; then
		id_start=$(echo $item_id | awk -F"-" '{print $1}')
		id_end=$(echo $item_id | awk -F"-" '{print $2}')
		for item_id_c in $(seq ${id_start} ${id_end}); do
			ITEM_ID_SQL_PARAMS="${ITEM_ID_SQL_PARAMS},${item_id_c}"
		done
	else
		ITEM_ID_SQL_PARAMS="${ITEM_ID_SQL_PARAMS},${item_id}"
	fi
	ITEM_ID_SQL_PARAMS=$(echo ${ITEM_ID_SQL_PARAMS}|sed "s/^,//")
done

if egrep -q "TEST|SUB|DATA|DLC|TIME" <<< "$HOST_NAME" ; then
	SET_NUMBER="1"
else
	SET_NUMBER=$(get_set $(awk -F_ '{print $1}' <<< "$HOST_NAME"))
fi
echo "GAMEDB: ${GAME_DB_NAME}${SET_NUMBER}" | colorize red black
echo "ITEM_ID_SQL_PARAMS: ${ITEM_ID_SQL_PARAMS}" | colorize green
echo "TABLES: ${ITEMID_RELATED_TABLES}" | colorize yellow
echo

VIEW_NAME_LISTS=""
CHECK_VIEW_QUERY="COPY (SELECT viewname FROM pg_views WHERE schemaname = 'public' AND viewname NOT LIKE '%auction_view_by_%' ORDER BY viewname) TO STDOUT;"
CHECK_VIEW_OUTPUT=$(psql -U postgres ${GAME_DB_NAME}${SET_NUMBER} -c "${CHECK_VIEW_QUERY}")
for view in ${CHECK_VIEW_OUTPUT}; do
	VIEW_NAME_LISTS="${VIEW_NAME_LISTS} ${view}"
done

for tables in ${ITEMID_RELATED_TABLES}; do
	if [[ $VIEW_NAME_LISTS == *"${tables}"* ]]; then
		if [ "${GAME_TYPE}" == "FF" ]; then
			split=10
		else
			split=2
		fi
		for num in $(seq 1 ${split}); do
			table="${tables}${num}"
			CHECK_SQL_QUERY="COPY (SELECT '$table' AS table, item_id, COUNT(durability), SUM(durability) FROM $table WHERE item_id IN (${ITEM_ID_SQL_PARAMS}) GROUP BY item_id ORDER BY item_id) TO STDOUT;"
			OUTPUT_SQL_QUERY="SELECT '$table' AS table, item_id, COUNT(durability), SUM(durability) FROM $table WHERE item_id IN (${ITEM_ID_SQL_PARAMS}) GROUP BY item_id ORDER BY item_id;"
			CHECK=$(psql -U postgres ${GAME_DB_NAME}${SET_NUMBER} -c "${CHECK_SQL_QUERY}")
			if [ ! -z "${CHECK}" ]; then
				psql -U postgres ${GAME_DB_NAME}${SET_NUMBER} -c "${OUTPUT_SQL_QUERY}"
			else
				echo "${table}: 0"
				echo
			fi
		done
	else
		table="${tables}"
		CHECK_SQL_QUERY="COPY (SELECT '$table' AS table, item_id, COUNT(durability), SUM(durability) FROM $table WHERE item_id IN (${ITEM_ID_SQL_PARAMS}) GROUP BY item_id ORDER BY item_id) TO STDOUT;"
		OUTPUT_SQL_QUERY="SELECT '$table' AS table, item_id, COUNT(durability), SUM(durability) FROM $table WHERE item_id IN (${ITEM_ID_SQL_PARAMS}) GROUP BY item_id ORDER BY item_id;"
		CHECK=$(psql -U postgres ${GAME_DB_NAME}${SET_NUMBER} -c "${CHECK_SQL_QUERY}")
		if [ ! -z "${CHECK}" ]; then
			psql -U postgres ${GAME_DB_NAME}${SET_NUMBER} -c "${OUTPUT_SQL_QUERY}"
		else
			echo "${table}: 0"
			echo
		fi
	fi
done
