#!/usr/bin/env python3
import coverage
import os, sys
import subprocess
from colorama import Fore, init


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from django.core.management import execute_from_command_line
init(autoreset=True)


bin_dir = os.path.abspath(os.path.join(sys.executable, os.path.pardir))
PERCENTAGE = 95
EXIT_CODE = 0


def check_if_exit_code():
    if EXIT_CODE != 0:
        exit(EXIT_CODE)


cov = coverage.Coverage(
    source=["project"],
    omit=["*/wsgi.py", "*/settings.py", "*/migrations/*.py", "*/__init__*", "*/tests.py"]
)
cov.start()


print(Fore.YELLOW + "Running Tests...")
execute_from_command_line([sys.argv[0], 'test'])
cov.stop()


print(Fore.YELLOW + "Collecting Coverage...")
cov.save()
cov.html_report()


covered = cov.report()
if covered <= PERCENTAGE:
    print(Fore.RED + "ERROR: Your coverage needs to be higher. Current coverage: {}%. Required: {}%.".format(covered, PERCENTAGE))
    EXIT_CODE = 1

check_if_exit_code()
print(Fore.GREEN + "Coverage Complete.")


FLAKE8_IGNORE = '--ignore=E128,E501,E401'
try:
    subprocess.check_output([os.path.join(bin_dir, 'flake8'), 'project', FLAKE8_IGNORE, '--exclude=migrations,settings,wsgi.py,__init__.py'])
    subprocess.check_output([os.path.join(bin_dir, 'flake8'), 'scripts', FLAKE8_IGNORE])
    subprocess.check_output([os.path.join(bin_dir, 'flake8'), sys.argv[0], FLAKE8_IGNORE])
except subprocess.CalledProcessError as e:
    print(Fore.RED + e.output.decode())
    EXIT_CODE = 1
check_if_exit_code()

print(Fore.GREEN + "All Python tests passed!")


EXIT_CODE = os.system('npm test')

check_if_exit_code()
print(Fore.GREEN + "All Tests Passed!")