import requests

import jingrow
from jingrow import _


def get_base_url():
	url = "https://jcloud.jingrow.com"
	if jingrow.conf.developer_mode and jingrow.conf.get("fc_base_url"):
		url = jingrow.conf.get("fc_base_url")
	return url


def get_site_login_url():
	return f"{get_base_url()}/dashboard/site-login"


def get_site_name():
	site_name = jingrow.local.site
	if jingrow.conf.developer_mode and jingrow.conf.get("saas_billing_site_name"):
		site_name = jingrow.conf.get("saas_billing_site_name")
	return site_name


def get_headers():
	# check if user is system manager
	if jingrow.get_roles(jingrow.session.user).count("System Manager") == 0:
		jingrow.throw(_("You are not allowed to access this resource"))

	# check if communication secret is set
	if not jingrow.conf.get("fc_communication_secret"):
		jingrow.throw(_("Communication secret not set"))

	return {
		"X-Site-Token": jingrow.conf.get("fc_communication_secret"),
		"X-Site-User": jingrow.session.user,
		"X-Site": get_site_name(),
	}


@jingrow.whitelist()
def current_site_info():
	from jingrow.utils import cint

	request = requests.post(f"{get_base_url()}/api/action/jcloud.saas.api.site.info", headers=get_headers())
	if request.status_code == 200:
		res = request.json().get("message")
		if not res:
			return None

		return {
			**res,
			"site_name": get_site_name(),
			"base_url": get_base_url(),
			"setup_complete": cint(jingrow.get_system_settings("setup_complete")),
		}

	else:
		jingrow.throw(_("Failed to get site info"))


@jingrow.whitelist()
def api(method, data=None):
	if data is None:
		data = {}
	request = requests.post(
		f"{get_base_url()}/api/action/jcloud.saas.api.{method}",
		headers=get_headers(),
		json=data,
	)
	if request.status_code == 200:
		return request.json().get("message")
	else:
		jingrow.throw(_("Failed while calling API {0}", method))


@jingrow.whitelist()
def is_fc_site() -> bool:
	is_system_manager = jingrow.get_roles(jingrow.session.user).count("System Manager")
	setup_completed = jingrow.get_system_settings("setup_complete")
	return bool(is_system_manager and setup_completed and jingrow.conf.get("fc_communication_secret"))


# login to jingrow cloud dashboard
@jingrow.whitelist()
def send_verification_code():
	request = requests.post(
		f"{get_base_url()}/api/action/jcloud.api.developer.saas.send_verification_code",
		headers=get_headers(),
		json={"domain": get_site_name()},
	)
	if request.status_code == 200:
		return request.json().get("message")
	else:
		jingrow.throw(_("Failed to request login to Jingrow Cloud"))


@jingrow.whitelist()
def verify_verification_code(verification_code: str, route: str):
	request = requests.post(
		f"{get_base_url()}/api/action/jcloud.api.developer.saas.verify_verification_code",
		headers=get_headers(),
		json={"domain": get_site_name(), "verification_code": verification_code, "route": route},
	)

	if request.status_code == 200:
		return {
			"base_url": get_base_url(),
			"login_token": request.json()["login_token"],
		}
	else:
		jingrow.throw(_("Invalid Code. Please try again."))
