#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from os import listdir
from os.path import isfile, join
import time
from opengate.helpers import *
import pathlib
import click
import hashlib

CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])


@click.command(context_settings=CONTEXT_SETTINGS)
@click.option("--test_id", "-i", default="all", help="Start test from this number")
def go(test_id):
    pathFile = pathlib.Path(__file__).parent.resolve()
    if "src" in os.listdir(pathFile):
        mypath = os.path.join(pathFile, "../tests/src")
    else:
        import opengate.tests

        mypath = os.path.join(
            pathlib.Path(opengate.tests.__file__).resolve().parent, "../tests/src"
        )

    print("Look for tests in: " + mypath)

    # look if the data for the tests are present
    if "patient-4mm.raw" not in listdir(os.path.join(mypath, "..", "data")):
        print(
            colored.stylize(
                "The data are not present in: " + os.path.join(mypath, "..", "data"),
                color_error,
            )
        )
        print("Download them with:")
        print("git submodule update --init --recursive")
        return False

    lfsFile = open(os.path.join(mypath, "..", "data", "patient-4mm.raw"), "rb")
    bytesLfsFile = lfsFile.read()
    readable_hash = hashlib.sha256(bytesLfsFile).hexdigest()
    if (
        not readable_hash
        == "91c3bbac271f75ac6cbeb413d892933f4b3369fa5a747a55004e113b31d1c84c"
    ):
        print(
            colored.stylize(
                "The data are not correct in: " + os.path.join(mypath, "..", "data"),
                color_error,
            )
        )
        print("Activate LFS and download them with:")
        print("git submodule update --init --recursive")
        return False

    onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

    files = []
    for f in onlyfiles:
        if "WIP" in f:
            print(f"Ignoring: {f:<40} (Work In Progress) ")
            continue
        if "visu" in f:
            continue
        if "test" not in f:
            continue
        if ".py" not in f:
            continue
        if ".log" in f:
            continue
        if "all_tes" in f:
            continue
        if "_base" in f:
            continue
        if f == "test045_speedup.py":
            continue
        if "_helpers" in f:
            continue
        files.append(f)

    files = sorted(files)
    if test_id != "all":
        test_id = int(test_id)
        files_new = []
        for f in files:
            id = int(f[4:7])
            if id >= test_id:
                files_new.append(f)
            else:
                print(f"Ignoring: {f:<40} (< {test_id}) ")
        files = files_new

    print(f"Running {len(files)} tests")
    print(f"-" * 70)

    failure = False

    for f in files:
        start = time.time()
        print(f"Running: {f:<46}  ", end="")
        cmd = "python " + os.path.join(mypath, f"{f}")
        log = os.path.join(os.path.dirname(mypath), f"log/{f}.log")
        r = os.system(f"{cmd} > {log}")
        # subprocess.run(cmd, stdout=f, shell=True, check=True)
        if r == 0:
            print(colored.stylize(" OK", color_ok), end="")
        else:
            if r == 2:
                # this is probably a Ctrl+C, so we stop
                gate.fatal("Stopped by user")
            else:
                print(colored.stylize(" FAILED !", color_error), end="")
                failure = True
                os.system("cat " + log)
        end = time.time()
        print(f"   {end - start:0.1f} s     {log:<65}")

    print(not failure)


# --------------------------------------------------------------------------
if __name__ == "__main__":
    go()
