# Copyright (c) 2021, JINGROW and Contributors
# MIT License. See LICENSE
"""
	jingrow.coverage
	~~~~~~~~~~~~~~~~

	Coverage settings for jingrow
"""

STANDARD_INCLUSIONS = ["*.py"]

STANDARD_EXCLUSIONS = [
	"*.js",
	"*.xml",
	"*.pyc",
	"*.css",
	"*.less",
	"*.scss",
	"*.vue",
	"*.html",
	"*/test_*",
	"*/node_modules/*",
	"*/pagetype/*/*_dashboard.py",
	"*/patches/*",
]

# tested via commands' test suite
TESTED_VIA_CLI = [
	"*/jingrow/installer.py",
	"*/jingrow/build.py",
	"*/jingrow/database/__init__.py",
	"*/jingrow/database/db_manager.py",
	"*/jingrow/database/**/setup_db.py",
]

JINGROW_EXCLUSIONS = [
	"*/tests/*",
	"*/commands/*",
	"*/jingrow/change_log/*",
	"*/jingrow/exceptions*",
	"*/jingrow/coverage.py",
	"*jingrow/setup.py",
	"*/pagetype/*/*_dashboard.py",
	"*/patches/*",
	*TESTED_VIA_CLI,
]


class CodeCoverage:
	def __init__(self, with_coverage, app):
		self.with_coverage = with_coverage
		self.app = app or "jingrow"

	def __enter__(self):
		if self.with_coverage:
			import os

			from coverage import Coverage

			from jingrow.utils import get_bench_path

			# Generate coverage report only for app that is being tested
			source_path = os.path.join(get_bench_path(), "apps", self.app)
			omit = STANDARD_EXCLUSIONS[:]

			if self.app == "jingrow":
				omit.extend(JINGROW_EXCLUSIONS)

			self.coverage = Coverage(source=[source_path], omit=omit, include=STANDARD_INCLUSIONS)
			self.coverage.start()

	def __exit__(self, exc_type, exc_value, traceback):
		if self.with_coverage:
			self.coverage.stop()
			self.coverage.save()
			self.coverage.xml_report()
			print("Saved Coverage")
