# Copyright (c) 2015, XhiveFramework Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE

# Database Module
# --------------------
from shutil import which

from xhiveframework.database.database import savepoint


def setup_database(force, source_sql=None, verbose=None, no_mariadb_socket=False):
	import xhiveframework

	if xhiveframework.conf.db_type == "postgres":
		import xhiveframework.database.postgres.setup_db

		return xhiveframework.database.postgres.setup_db.setup_database(force, source_sql, verbose)
	else:
		import xhiveframework.database.mariadb.setup_db

		return xhiveframework.database.mariadb.setup_db.setup_database(
			force, source_sql, verbose, no_mariadb_socket=no_mariadb_socket
		)


def drop_user_and_database(db_name, root_login=None, root_password=None):
	import xhiveframework

	if xhiveframework.conf.db_type == "postgres":
		import xhiveframework.database.postgres.setup_db

		return xhiveframework.database.postgres.setup_db.drop_user_and_database(db_name, root_login, root_password)
	else:
		import xhiveframework.database.mariadb.setup_db

		return xhiveframework.database.mariadb.setup_db.drop_user_and_database(db_name, root_login, root_password)


def get_db(host=None, user=None, password=None, port=None):
	import xhiveframework

	if xhiveframework.conf.db_type == "postgres":
		import xhiveframework.database.postgres.database

		return xhiveframework.database.postgres.database.PostgresDatabase(host, user, password, port=port)
	else:
		import xhiveframework.database.mariadb.database

		return xhiveframework.database.mariadb.database.MariaDBDatabase(host, user, password, port=port)


def get_command(host=None, port=None, user=None, password=None, db_name=None, extra=None, dump=False):
	import xhiveframework

	if xhiveframework.conf.db_type == "postgres":
		if dump:
			bin, bin_name = which("pg_dump"), "pg_dump"
		else:
			bin, bin_name = which("psql"), "psql"

		if password:
			conn_string = f"postgresql://{user}:{password}@{host}:{port}/{db_name}"
		else:
			conn_string = f"postgresql://{user}@{host}:{port}/{db_name}"

		command = [conn_string]

		if extra:
			command.extend(extra)

	else:
		if dump:
			bin, bin_name = which("mariadb-dump") or which("mysqldump"), "mariadb-dump"
		else:
			bin, bin_name = which("mariadb") or which("mysql"), "mariadb"

		command = [
			f"--user={user}",
			f"--host={host}",
			f"--port={port}",
		]

		if password:
			command.append(f"--password={password}")

		if dump:
			command.extend(
				[
					"--single-transaction",
					"--quick",
					"--lock-tables=false",
				]
			)
		else:
			command.extend(
				[
					"--pager=less -SFX",
					"--safe-updates",
					"--no-auto-rehash",
				]
			)

		command.append(db_name)

		if extra:
			command.extend(extra)

	return bin, command, bin_name
