# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE

from cryptography.fernet import Fernet, InvalidToken
from passlib.context import CryptContext
from pypika.terms import Values

import jingrow
from jingrow import _
from jingrow.query_builder import Table
from jingrow.utils import cstr, encode

Auth = Table("__Auth")


passlibctx = CryptContext(
	schemes=[
		"pbkdf2_sha256",
		"argon2",
	],
)


def get_decrypted_password(pagetype, name, fieldname="password", raise_exception=True):
	result = (
		jingrow.qb.from_(Auth)
		.select(Auth.password)
		.where(
			(Auth.pagetype == pagetype)
			& (Auth.name == name)
			& (Auth.fieldname == fieldname)
			& (Auth.encrypted == 1)
		)
		.limit(1)
	).run()

	if result and result[0][0]:
		return decrypt(result[0][0], key=f"{pagetype}.{name}.{fieldname}")

	elif raise_exception:
		jingrow.throw(
			_("Password not found for {0} {1} {2}").format(pagetype, name, fieldname),
			jingrow.AuthenticationError,
		)


def set_encrypted_password(pagetype, name, pwd, fieldname="password"):
	query = (
		jingrow.qb.into(Auth)
		.columns(Auth.pagetype, Auth.name, Auth.fieldname, Auth.password, Auth.encrypted)
		.insert(pagetype, name, fieldname, encrypt(pwd), 1)
	)

	# TODO: Simplify this via aliasing methods in `jingrow.qb`
	if jingrow.db.db_type == "mariadb":
		query = query.on_duplicate_key_update(Auth.password, Values(Auth.password))
	elif jingrow.db.db_type == "postgres":
		query = query.on_conflict(Auth.pagetype, Auth.name, Auth.fieldname).do_update(Auth.password)

	try:
		query.run()

	except jingrow.db.DataError as e:
		if jingrow.db.is_data_too_long(e):
			jingrow.throw(_("Most probably your password is too long."), exc=e)
		raise e


def remove_encrypted_password(pagetype, name, fieldname="password"):
	jingrow.db.delete("__Auth", {"pagetype": pagetype, "name": name, "fieldname": fieldname})


def check_password(user, pwd, pagetype="User", fieldname="password", delete_tracker_cache=True):
	"""Checks if user and password are correct, else raises jingrow.AuthenticationError"""

	result = (
		jingrow.qb.from_(Auth)
		.select(Auth.name, Auth.password)
		.where(
			(Auth.pagetype == pagetype)
			& (Auth.name == user)
			& (Auth.fieldname == fieldname)
			& (Auth.encrypted == 0)
		)
		.limit(1)
		.run(as_dict=True)
	)

	if not result or not passlibctx.verify(pwd, result[0].password):
		raise jingrow.AuthenticationError(_("Incorrect User or Password"))

	# lettercase agnostic
	user = result[0].name

	# TODO: This need to be deleted after checking side effects of it.
	# We have a `LoginAttemptTracker` that can take care of tracking related cache.
	if delete_tracker_cache:
		delete_login_failed_cache(user)

	if passlibctx.needs_update(result[0].password):
		update_password(user, pwd, pagetype, fieldname)

	return user


def delete_login_failed_cache(user):
	jingrow.cache.hdel("last_login_tried", user)
	jingrow.cache.hdel("login_failed_count", user)
	jingrow.cache.hdel("locked_account_time", user)


def update_password(user, pwd, pagetype="User", fieldname="password", logout_all_sessions=False):
	"""
	Update the password for the User

	:param user: username
	:param pwd: new password
	:param pagetype: pagetype name (for encryption)
	:param fieldname: fieldname (in given pagetype) (for encryption)
	:param logout_all_session: delete all other session
	"""
	hashPwd = passlibctx.hash(pwd)

	query = (
		jingrow.qb.into(Auth)
		.columns(Auth.pagetype, Auth.name, Auth.fieldname, Auth.password, Auth.encrypted)
		.insert(pagetype, user, fieldname, hashPwd, 0)
	)

	# TODO: Simplify this via aliasing methods in `jingrow.qb`
	if jingrow.db.db_type == "mariadb":
		query = query.on_duplicate_key_update(Auth.password, hashPwd).on_duplicate_key_update(
			Auth.encrypted, 0
		)
	elif jingrow.db.db_type == "postgres":
		query = (
			query.on_conflict(Auth.pagetype, Auth.name, Auth.fieldname)
			.do_update(Auth.password, hashPwd)
			.do_update(Auth.encrypted, 0)
		)

	query.run()

	# clear all the sessions except current
	if logout_all_sessions:
		from jingrow.sessions import clear_sessions

		clear_sessions(user=user, keep_current=True, force=True)


def delete_all_passwords_for(pagetype, name):
	try:
		jingrow.db.delete("__Auth", {"pagetype": pagetype, "name": name})
	except Exception as e:
		if not jingrow.db.is_missing_column(e):
			raise


def rename_password(pagetype, old_name, new_name):
	# NOTE: fieldname is not considered, since the document is renamed
	jingrow.qb.update(Auth).set(Auth.name, new_name).where(
		(Auth.pagetype == pagetype) & (Auth.name == old_name)
	).run()


def rename_password_field(pagetype, old_fieldname, new_fieldname):
	jingrow.qb.update(Auth).set(Auth.fieldname, new_fieldname).where(
		(Auth.pagetype == pagetype) & (Auth.fieldname == old_fieldname)
	).run()


def create_auth_table():
	# same as Framework.sql
	jingrow.db.create_auth_table()


def encrypt(txt, encryption_key=None):
	# Only use Fernet.generate_key().decode() to enter encyption_key value

	try:
		cipher_suite = Fernet(encode(encryption_key or get_encryption_key()))
	except Exception:
		# encryption_key is not in 32 url-safe base64-encoded format
		jingrow.throw(_("Encryption key is in invalid format!"))

	return cstr(cipher_suite.encrypt(encode(txt)))


def decrypt(txt, encryption_key=None, key: str | None = None):
	# Only use encryption_key value generated with Fernet.generate_key().decode()

	try:
		cipher_suite = Fernet(encode(encryption_key or get_encryption_key()))
		return cstr(cipher_suite.decrypt(encode(txt)))
	except InvalidToken:
		# encryption_key in site_config is changed and not valid
		jingrow.throw(
			(_("Failed to decrypt key {0}").format(key) + "<br><br>" if key else "")
			+ _("Encryption key is invalid! Please check site_config.json")
			+ "<br><br>"
			+ _(
				"If you have recently restored the site you may need to copy the site config contaning original Encryption Key."
			)
			+ "<br><br>"
			+ _(
				"Please visit https://jcloud.jingrow.com/pages/sites/migrate-an-existing-site#encryption-key for more information."
			),
		)


def get_encryption_key():
	if "encryption_key" not in jingrow.local.conf:
		from jingrow.installer import update_site_config

		encryption_key = Fernet.generate_key().decode()
		update_site_config("encryption_key", encryption_key)
		jingrow.local.conf.encryption_key = encryption_key

	return jingrow.local.conf.encryption_key


def get_password_reset_limit():
	return jingrow.get_system_settings("password_reset_limit") or 3
