# Copyright (c) 2020, JINGROW and Contributors
# License: MIT. See LICENSE

import jingrow
import jingrow.monitor
from jingrow.monitor import MONITOR_REDIS_KEY, get_trace_id
from jingrow.tests.utils import JingrowTestCase
from jingrow.utils import set_request
from jingrow.utils.response import build_response


class TestMonitor(JingrowTestCase):
	def setUp(self):
		jingrow.conf.monitor = 1
		jingrow.cache.delete_value(MONITOR_REDIS_KEY)

	def tearDown(self):
		jingrow.conf.monitor = 0
		jingrow.cache.delete_value(MONITOR_REDIS_KEY)

	def test_enable_monitor(self):
		set_request(method="GET", path="/api/action/jingrow.ping")
		response = build_response("json")

		jingrow.monitor.start()
		jingrow.monitor.stop(response)

		logs = jingrow.cache.lrange(MONITOR_REDIS_KEY, 0, -1)
		self.assertEqual(len(logs), 1)

		log = jingrow.parse_json(logs[0].decode())
		self.assertTrue(log.duration)
		self.assertTrue(log.site)
		self.assertTrue(log.timestamp)
		self.assertTrue(log.uuid)
		self.assertTrue(log.request)
		self.assertEqual(log.transaction_type, "request")
		self.assertEqual(log.request["method"], "GET")

	def test_no_response(self):
		set_request(method="GET", path="/api/action/jingrow.ping")

		jingrow.monitor.start()
		jingrow.monitor.stop(response=None)

		logs = jingrow.cache.lrange(MONITOR_REDIS_KEY, 0, -1)
		self.assertEqual(len(logs), 1)

		log = jingrow.parse_json(logs[0].decode())
		self.assertEqual(log.request["status_code"], 500)
		self.assertEqual(log.transaction_type, "request")
		self.assertEqual(log.request["method"], "GET")

	def test_job(self):
		jingrow.utils.background_jobs.execute_job(
			jingrow.local.site, "jingrow.ping", None, None, {}, is_async=False
		)

		logs = jingrow.cache.lrange(MONITOR_REDIS_KEY, 0, -1)
		self.assertEqual(len(logs), 1)
		log = jingrow.parse_json(logs[0].decode())
		self.assertEqual(log.transaction_type, "job")
		self.assertTrue(log.job)
		self.assertEqual(log.job["method"], "jingrow.ping")
		self.assertEqual(log.job["scheduled"], False)
		self.assertEqual(log.job["wait"], 0)

	def test_flush(self):
		set_request(method="GET", path="/api/action/jingrow.ping")
		response = build_response("json")
		jingrow.monitor.start()
		jingrow.monitor.stop(response)

		open(jingrow.monitor.log_file(), "w").close()
		jingrow.monitor.flush()

		with open(jingrow.monitor.log_file()) as f:
			logs = f.readlines()

		self.assertEqual(len(logs), 1)
		log = jingrow.parse_json(logs[0])
		self.assertEqual(log.transaction_type, "request")

	def test_trace_ids(self):
		set_request(method="GET", path="/api/action/jingrow.ping")
		response = build_response("json")
		jingrow.monitor.start()
		jingrow.db.sql("select 1")
		self.assertIn(get_trace_id(), str(jingrow.db.last_query))
		jingrow.monitor.stop(response)
