#! /usr/bin/python3
# Copyright (C) 2018-2020 Merspieler, merspieler _at_ airmail.cc
#
# 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; either version 3 of the
# License, or (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import sys
import json
import os
import pymysql
from time import sleep

from common import norm

verbose = False
dbuser = ""
dbpw = ""
dbname = "worldbuild"
fname = ""
repeat = 0

argc = len(sys.argv)
i = 1
while i < argc:
	if sys.argv[i] == "--port":
		i += 1
		port = int(sys.argv[i])
	elif sys.argv[i] == "--host":
		i += 1
		host = sys.argv[i]
	elif sys.argv[i] == "-f" or sys.argv[i] == "--file":
		i += 1
		fname = sys.argv[i]
	elif sys.argv[i] == "-u" or sys.argv[i] == "--user":
		i += 1
		dbuser = sys.argv[i]
	elif sys.argv[i] == "-p" or sys.argv[i] == "--password":
		i += 1
		dbpw = sys.argv[i]
	elif sys.argv[i] == "-d" or sys.argv[i] == "--database":
		i += 1
		dbname = sys.argv[i]
	elif sys.argv[i] == "-r" or sys.argv[i] == "--repeat":
		i += 1
		repeat = int(sys.argv[i])
	elif sys.argv[i] == "-v":
		verbose = True
	elif sys.argv[i] == "-h" or sys.argv[i] == "--help":
		print("usage: get-progress.py [OPTIONS]")
		print("Writes the procgress to json file")
		print("")
		print("OPTIONS")
		print("  -f, --file        Output file")
		print("  -u, --user        Database user")
		print("  -p, --password    Database password")
		print("  -d, --database    Database to be used. Default: worldbuild")
		print("  -v, --verbose     Verbose printouts")
		print("  -r, --repeat      If set, run every <n> minutes else run once")
		print("  -h, --help        Shows this help and exit")
		sys.exit(0)
	else:
		print("Unknown option " + sys.argv[i])
		sys.exit(1)
	i += 1

if dbuser == "":
	print("ERROR: No database user given")
	sys.exit(1)

if dbpw == "":
	print("ERROR: No database password given")
	sys.exit(1)

if fname == "":
	print("ERROR: No file name given")
	sys.exit(1)

db = pymysql.connect("localhost", dbuser, dbpw, dbname)

cursor = db.cursor()

try:
	while True:
		sql = "SELECT topLevel.name AS topLevelName, status.name AS statusName, COUNT(*) AS sCount from secondLevel JOIN topLevel ON secondLevel.parent_id = topLevel.id JOIN status ON secondLevel.status_id = status.id GROUP BY status.id, topLevelName"
		cursor.execute(sql)
		rows = cursor.fetchall()

		status = {}
		for row in rows:
			if not row[0] in status:
				status[row[0]] = {}
			status[row[0]][row[1]] = row[2]

		sql = "SELECT topLevel.name, status.name FROM topLevel JOIN status ON topLevel.status_id = status.id"
		cursor.execute(sql)
		rows = cursor.fetchall()

		for row in rows:
			status[row[0]]["status"] = row[1]

		try:
			with open(fname, "w") as f:
				json.dump(status, f, indent=4)
		except IOError:
			print("ERROR: Failed to write to file")

		if repeat == 0:
			sys.exit(0)
		else:
			sleep(repeat * 60)
		db.commit()
except KeyboardInterrupt:
	print("Exiting...")