# Copyright (c) 2020, JINGROW
# For license information, please see license.txt


import os

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

from jcloud.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 execute():
	settings = jingrow.get_single("Jcloud 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 = lambda self: jingrow.db.truncate("Agent Request Failure")

	# 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(
			"Jcloud Settings", "stripe_publishable_key", publishable_key
		)
		jingrow.db.set_single_value("Jcloud Settings", "stripe_secret_key", secret_key)
