# Copyright (c) 2015, InfluxFramework LLC
# License: MIT. See LICENSE

import influxframework
import influxframework.utils
from influxframework import _
from influxframework.auth import LoginManager
from influxframework.integrations.doctype.ldap_settings.ldap_settings import LDAPSettings
from influxframework.integrations.oauth2_logins import decoder_compat
from influxframework.utils import cint
from influxframework.utils.html_utils import get_icon_html
from influxframework.utils.jinja import guess_is_path
from influxframework.utils.oauth import (
	get_oauth2_authorize_url,
	get_oauth_keys,
	login_via_oauth2,
	login_via_oauth2_id_token,
	redirect_post_login,
)
from influxframework.utils.password import get_decrypted_password
from influxframework.website.utils import get_home_page

no_cache = True


def get_context(context):
	redirect_to = influxframework.local.request.args.get("redirect-to")

	if influxframework.session.user != "Guest":
		if not redirect_to:
			if influxframework.session.data.user_type == "Website User":
				redirect_to = get_home_page()
			else:
				redirect_to = "/app"

		if redirect_to != "login":
			influxframework.local.flags.redirect_location = redirect_to
			raise influxframework.Redirect

	context.no_header = True
	context.for_test = "login.html"
	context["title"] = "Login"
	context["provider_logins"] = []
	context["disable_signup"] = cint(influxframework.get_website_settings("disable_signup"))
	context["disable_user_pass_login"] = cint(influxframework.get_system_settings("disable_user_pass_login"))
	context["logo"] = influxframework.get_website_settings("app_logo") or influxframework.get_hooks("app_logo_url")[-1]
	context["app_name"] = (
		influxframework.get_website_settings("app_name") or influxframework.get_system_settings("app_name") or _("InfluxFramework")
	)

	signup_form_template = influxframework.get_hooks("signup_form_template")
	if signup_form_template and len(signup_form_template):
		path = signup_form_template[-1]
		if not guess_is_path(path):
			path = influxframework.get_attr(signup_form_template[-1])()
	else:
		path = "influxframework/templates/signup.html"

	if path:
		context["signup_form_template"] = influxframework.get_template(path).render()

	providers = influxframework.get_all(
		"Social Login Key",
		filters={"enable_social_login": 1},
		fields=["name", "client_id", "base_url", "provider_name", "icon"],
		order_by="name",
	)

	for provider in providers:
		client_secret = get_decrypted_password("Social Login Key", provider.name, "client_secret")
		if not client_secret:
			continue

		icon = None
		if provider.icon:
			if provider.provider_name == "Custom":
				icon = get_icon_html(provider.icon, small=True)
			else:
				icon = f"<img src='{provider.icon}' alt={provider.provider_name}>"

		if provider.client_id and provider.base_url and get_oauth_keys(provider.name):
			context.provider_logins.append(
				{
					"name": provider.name,
					"provider_name": provider.provider_name,
					"auth_url": get_oauth2_authorize_url(provider.name, redirect_to),
					"icon": icon,
				}
			)
			context["social_login"] = True

	context["ldap_settings"] = LDAPSettings.get_ldap_client_settings()

	login_label = [_("Email")]

	if influxframework.utils.cint(influxframework.get_system_settings("allow_login_using_mobile_number")):
		login_label.append(_("Mobile"))

	if influxframework.utils.cint(influxframework.get_system_settings("allow_login_using_user_name")):
		login_label.append(_("Username"))

	context["login_label"] = f" {_('or')} ".join(login_label)

	return context


@influxframework.whitelist(allow_guest=True)
def login_via_google(code, state):
	login_via_oauth2("google", code, state, decoder=decoder_compat)


@influxframework.whitelist(allow_guest=True)
def login_via_github(code, state):
	login_via_oauth2("github", code, state)


@influxframework.whitelist(allow_guest=True)
def login_via_facebook(code, state):
	login_via_oauth2("facebook", code, state, decoder=decoder_compat)


@influxframework.whitelist(allow_guest=True)
def login_via_influxframework(code, state):
	login_via_oauth2("influxframework", code, state, decoder=decoder_compat)


@influxframework.whitelist(allow_guest=True)
def login_via_office365(code, state):
	login_via_oauth2_id_token("office_365", code, state, decoder=decoder_compat)


@influxframework.whitelist(allow_guest=True)
def login_via_token(login_token):
	sid = influxframework.cache().get_value(f"login_token:{login_token}", expires=True)
	if not sid:
		influxframework.respond_as_web_page(_("Invalid Request"), _("Invalid Login Token"), http_status_code=417)
		return

	influxframework.local.form_dict.sid = sid
	influxframework.local.login_manager = LoginManager()

	redirect_post_login(
		desk_user=influxframework.db.get_value("User", influxframework.session.user, "user_type") == "System User"
	)
