import os

import xhiveframework
from xhiveframework.database.db_manager import DbManager


def setup_database(force, source_sql=None, verbose=False):
	root_conn = get_root_connection(xhiveframework.flags.root_login, xhiveframework.flags.root_password)
	root_conn.commit()
	root_conn.sql("end")
	root_conn.sql(f"DROP DATABASE IF EXISTS `{xhiveframework.conf.db_name}`")
	root_conn.sql(f"DROP USER IF EXISTS {xhiveframework.conf.db_name}")
	root_conn.sql(f"CREATE DATABASE `{xhiveframework.conf.db_name}`")
	root_conn.sql(f"CREATE user {xhiveframework.conf.db_name} password '{xhiveframework.conf.db_password}'")
	root_conn.sql(f"GRANT ALL PRIVILEGES ON DATABASE `{xhiveframework.conf.db_name}` TO {xhiveframework.conf.db_name}")
	root_conn.close()

	bootstrap_database(xhiveframework.conf.db_name, verbose, source_sql=source_sql)
	xhiveframework.connect()


def bootstrap_database(db_name, verbose, source_sql=None):
	xhiveframework.connect(db_name=db_name)
	import_db_from_sql(source_sql, verbose)
	xhiveframework.connect(db_name=db_name)

	if "tabDefaultValue" not in xhiveframework.db.get_tables():
		import sys

		from click import secho

		secho(
			"Table 'tabDefaultValue' missing in the restored site. "
			"This may be due to incorrect permissions or the result of a restore from a bad backup file. "
			"Database not installed correctly.",
			fg="red",
		)
		sys.exit(1)


def import_db_from_sql(source_sql=None, verbose=False):
	if verbose:
		print("Starting database import...")
	db_name = xhiveframework.conf.db_name
	if not source_sql:
		source_sql = os.path.join(os.path.dirname(__file__), "framework_postgres.sql")
	DbManager(xhiveframework.local.db).restore_database(
		verbose, db_name, source_sql, db_name, xhiveframework.conf.db_password
	)
	if verbose:
		print("Imported from database %s" % source_sql)


def get_root_connection(root_login=None, root_password=None):
	if not xhiveframework.local.flags.root_connection:
		if not root_login:
			root_login = xhiveframework.conf.get("root_login") or None

		if not root_login:
			root_login = input("Enter postgres super user: ")

		if not root_password:
			root_password = xhiveframework.conf.get("root_password") or None

		if not root_password:
			from getpass import getpass

			root_password = getpass("Postgres super user password: ")

		xhiveframework.local.flags.root_connection = xhiveframework.database.get_db(
			host=xhiveframework.conf.db_host,
			port=xhiveframework.conf.db_port,
			user=root_login,
			password=root_password,
		)

	return xhiveframework.local.flags.root_connection


def drop_user_and_database(db_name, root_login, root_password):
	root_conn = get_root_connection(
		xhiveframework.flags.root_login or root_login, xhiveframework.flags.root_password or root_password
	)
	root_conn.commit()
	root_conn.sql(
		"SELECT pg_terminate_backend (pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = %s",
		(db_name,),
	)
	root_conn.sql("end")
	root_conn.sql(f"DROP DATABASE IF EXISTS {db_name}")
	root_conn.sql(f"DROP USER IF EXISTS {db_name}")
