# Copyright (c) 2019, XhiveFramework Technologies and contributors
# License: MIT. See LICENSE

import datetime
import json
from urllib.parse import parse_qs

import xhiveframework
from xhiveframework import _
from xhiveframework.utils import get_request_session


def make_request(method, url, auth=None, headers=None, data=None, json=None, params=None):
	auth = auth or ""
	data = data or {}
	headers = headers or {}

	try:
		s = get_request_session()
		xhiveframework.flags.integration_request = s.request(
			method, url, data=data, auth=auth, headers=headers, json=json, params=params
		)
		xhiveframework.flags.integration_request.raise_for_status()

		if xhiveframework.flags.integration_request.headers.get("content-type") == "text/plain; charset=utf-8":
			return parse_qs(xhiveframework.flags.integration_request.text)

		return xhiveframework.flags.integration_request.json()
	except Exception as exc:
		xhiveframework.log_error()
		raise exc


def make_get_request(url, **kwargs):
	return make_request("GET", url, **kwargs)


def make_post_request(url, **kwargs):
	return make_request("POST", url, **kwargs)


def make_put_request(url, **kwargs):
	return make_request("PUT", url, **kwargs)


def make_patch_request(url, **kwargs):
	return make_request("PATCH", url, **kwargs)


def make_delete_request(url, **kwargs):
	return make_request("DELETE", url, **kwargs)


def create_request_log(
	data,
	integration_type=None,
	service_name=None,
	name=None,
	error=None,
	request_headers=None,
	output=None,
	**kwargs,
):
	"""
	DEPRECATED: The parameter integration_type will be removed in the next major release.
	Use is_remote_request instead.
	"""
	if integration_type == "Remote":
		kwargs["is_remote_request"] = 1

	elif integration_type == "Subscription Notification":
		kwargs["request_description"] = integration_type

	reference_doctype = reference_docname = None
	if "reference_doctype" not in kwargs:
		if isinstance(data, str):
			data = json.loads(data)

		reference_doctype = data.get("reference_doctype")
		reference_docname = data.get("reference_docname")

	integration_request = xhiveframework.get_doc(
		{
			"doctype": "Integration Request",
			"integration_request_service": service_name,
			"request_headers": get_json(request_headers),
			"data": get_json(data),
			"output": get_json(output),
			"error": get_json(error),
			"reference_doctype": reference_doctype,
			"reference_docname": reference_docname,
			**kwargs,
		}
	)

	if name:
		integration_request.flags._name = name

	integration_request.insert(ignore_permissions=True)
	xhiveframework.db.commit()

	return integration_request


def get_json(obj):
	return obj if isinstance(obj, str) else xhiveframework.as_json(obj, indent=1)


def json_handler(obj):
	if isinstance(obj, datetime.date | datetime.timedelta | datetime.datetime):
		return str(obj)
