# coding=utf-8
"""
Test Suite.

.. note:: This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation; either version 2 of the License, or
     (at your option) any later version.

"""

import os
import sys
import tempfile
import unittest

import qgis  # pylint: disable=unused-import # noqa F401
from osgeo import gdal

from geest.utilities import log_message

try:
    from pip import main as pipmain
except ImportError:
    from pip._internal import main as pipmain

try:
    import coverage
except ImportError:
    pipmain(["install", "coverage"])
    import coverage

__author__ = "Alessandro Pasotti"
__revision__ = "$Format:%H$"
__date__ = "30/04/2018"
__copyright__ = "Copyright 2018, North Road"


def _run_tests(test_suite, package_name, with_coverage=False):
    """Core function to test a test suite.

    Args:
        test_suite: The test suite to run.
        package_name: Name of the package being tested.
        with_coverage: Whether to run with coverage tracking.
    """
    count = test_suite.countTestCases()
    log_message("########")
    log_message("%s tests has been discovered in %s" % (count, package_name))
    log_message("Python GDAL : %s" % gdal.VersionInfo("VERSION_NUM"))
    log_message("########")
    if with_coverage:
        cov = coverage.Coverage(
            source=["/vector_correction"],
            omit=["*/test/*"],
        )
        cov.start()

    unittest.TextTestRunner(verbosity=3, stream=sys.stdout).run(test_suite)

    if with_coverage:
        cov.stop()
        cov.save()
        # pylint: disable=consider-using-with
        report = tempfile.NamedTemporaryFile(delete=False)
        cov.report(file=report)
        # Produce HTML reports in the `htmlcov` folder and open index.html
        # cov.html_report()
        report.close()
        with open(report.name, "r", encoding="utf8") as fin:
            log_message(fin.read())


def test_package(package="animation_workbench"):
    """Test package.
    This function is called by travis without arguments.

    Args:
        package: The package to test.
    """
    test_loader = unittest.defaultTestLoader
    try:
        test_suite = test_loader.discover(package)
    except ImportError:
        test_suite = unittest.TestSuite()
    _run_tests(test_suite, package)


def test_environment():
    """Test package with an environment variable."""
    package = os.environ.get("TESTING_PACKAGE", "animation_workbench")
    test_loader = unittest.defaultTestLoader
    test_suite = test_loader.discover(package)
    _run_tests(test_suite, package)


if __name__ == "__main__":
    test_package()
