# Copyright (c) 2020, Jingrow Technologies Pvt. Ltd. and Contributors
# For license information, please see license.txt


import os
from contextlib import contextmanager
from typing import Any

import jingrow
from jingrow import set_user as _set_user
from jingrow.model.page import Page
from jingrow.tests.utils import JingrowTestCase

from jcloude.utils import _get_current_team, _system_user


def pg_equal(self: Page, other: Page) -> bool:
	"""Partial equality checking of Page object"""
	if not isinstance(other, Page):
		return False
	if self.pagetype == other.pagetype and self.name == other.name:
		return True
	return False


def JingrowTestCase_setUp(self) -> None:
	jingrow.clear_cache()
	jingrow.db.truncate("Agent Request Failure")
	jingrow.local.conf.update({"throttle_user_limit": 600})


def execute():
	settings = jingrow.get_single("Jcloude Settings")
	if not (settings.stripe_secret_key and settings.stripe_publishable_key):
		create_test_stripe_credentials()
	import cssutils

	# Silence the cssutils errors that are mostly pointless
	cssutils.log.setLevel(50)

	# Monkey patch certain methods for when tests are running
	Page.__eq__ = pg_equal

	JingrowTestCase.setUp = JingrowTestCase_setUp
	JingrowTestCase.tearDown = lambda self: jingrow.db.rollback()
	JingrowTestCase.freeze_time = staticmethod(freeze_time)

	# patch jingrow.set_user that
	jingrow.set_user = set_user_with_current_team

	# jingrow.local.team helper
	jingrow.local.team = _get_current_team
	jingrow.local.system_user = _system_user


def set_user_with_current_team(user):
	_set_user(user)
	jingrow.local._current_team = None


def create_test_stripe_credentials():
	publishable_key = os.environ.get("STRIPE_PUBLISHABLE_KEY")
	secret_key = os.environ.get("STRIPE_SECRET_KEY")

	if publishable_key and secret_key:
		jingrow.db.set_single_value("Jcloude Settings", "stripe_publishable_key", publishable_key)
		jingrow.db.set_single_value("Jcloude Settings", "stripe_secret_key", secret_key)


@contextmanager
def freeze_time(time_to_freeze: Any, is_utc: bool = False, *args: Any, **kwargs: Any):
	"""freeze time using freezegun, compatible with Python 3.10 and 3.11+."""
	try:
		from datetime import UTC
	except ImportError:
		from datetime import timezone

		UTC = timezone.utc

	from zoneinfo import ZoneInfo

	from jingrow.utils.data import get_datetime, get_system_timezone
	from freezegun import freeze_time as freezegun_freeze_time

	if not is_utc:
		time_to_freeze = (
			get_datetime(time_to_freeze).replace(tzinfo=ZoneInfo(get_system_timezone())).astimezone(UTC)
		)

	with freezegun_freeze_time(time_to_freeze, *args, **kwargs):
		yield
