################################################## Tests ##############################################################


# XXX OBSOLETE ??? XXX

import requests
import os

from app import models
from app.api import bp, requested_format
from app.api.auth import token_auth
from app.api.errors import error_response

SCODOC_USER = "test"
SCODOC_PASSWORD = "test"
SCODOC_URL = "http://192.168.1.12:5000"
CHECK_CERTIFICATE = bool(int(os.environ.get("CHECK_CERTIFICATE", False)))

HEADERS = None


def get_token():
    """
    Permet de set le token dans le header
    """
    global HEADERS
    global SCODOC_USER
    global SCODOC_PASSWORD

    r0 = requests.post(
        SCODOC_URL + "/ScoDoc/api/tokens", auth=(SCODOC_USER, SCODOC_PASSWORD)
    )
    token = r0.json()["token"]
    HEADERS = {"Authorization": f"Bearer {token}"}


DEPT = None
FORMSEMESTRE = None
ETU = None


@bp.route("/test_dept", methods=["GET"])
def get_departement():
    """
    Permet de tester departements() mais également de set un département dans DEPT pour la suite des tests
    """

    get_token()

    global HEADERS
    global CHECK_CERTIFICATE
    global SCODOC_USER
    global SCODOC_PASSWORD

    # print(HEADERS)
    # departements
    r = requests.get(
        SCODOC_URL + "/ScoDoc/api/departements",
        headers=HEADERS,
        verify=CHECK_CERTIFICATE,
    )

    if r.status_code == 200:
        dept_id = r.json()[0]
        # print(dept_id)

        dept = models.Departement.query.filter_by(id=dept_id).first()
        dept = dept.to_dict()

        fields = ["id", "acronym", "description", "visible", "date_creation"]

        for field in dept:
            if field not in fields:
                return error_response(501, field + " field missing")

        global DEPT
        DEPT = dept

        return error_response(200, "OK")

    return error_response(409, "La requête ne peut être traitée en l’état actuel")


@bp.route("/test_formsemestre", methods=["GET"])
def get_formsemestre():
    """
    Permet de tester liste_semestres_courant() mais également de set un formsemestre dans FORMSEMESTRE
    pour la suite des tests
    """
    get_departement()

    global DEPT
    dept_acronym = DEPT["acronym"]

    # liste_semestres_courant
    r = requests.get(
        SCODOC_URL + "/ScoDoc/api/departements/" + dept_acronym + "/semestres_courants",
        auth=(SCODOC_USER, SCODOC_PASSWORD),
    )

    if r.status_code == 200:
        formsemestre = r.json()[0]
        print(r.json()[0])

        fields = [
            "gestion_semestrielle",
            "titre",
            "scodoc7_id",
            "date_debut",
            "bul_bgcolor",
            "date_fin",
            "resp_can_edit",
            "dept_id",
            "etat",
            "resp_can_change_ens",
            "id",
            "modalite",
            "ens_can_edit_eval",
            "formation_id",
            "gestion_compensation",
            "elt_sem_apo",
            "semestre_id",
            "bul_hide_xml",
            "elt_annee_apo",
            "block_moyennes",
            "formsemestre_id",
            "titre_num",
            "date_debut_iso",
            "date_fin_iso",
            "responsables",
        ]

        for field in formsemestre:
            if field not in fields:
                return error_response(501, field + " field missing")

        global FORMSEMESTRE
        FORMSEMESTRE = formsemestre

        return error_response(200, "OK")

    return error_response(409, "La requête ne peut être traitée en l’état actuel")


@bp.route("/test_etu", methods=["GET"])
def get_etudiant():
    """
    Permet de tester etudiants() mais également de set un etudiant dans ETU pour la suite des tests
    """

    # etudiants
    r = requests.get(
        SCODOC_URL + "/ScoDoc/api/etudiants/courant",
        auth=(SCODOC_USER, SCODOC_PASSWORD),
    )

    if r.status_code == 200:
        etu = r.json()[0]

        fields = [
            "civilite",
            "code_ine",
            "code_nip",
            "date_naissance",
            "email",
            "emailperso",
            "etudid",
            "nom",
            "prenom",
        ]

        for field in etu:
            if field not in fields:
                return error_response(501, field + " field missing")

        global ETU
        ETU = etu
        print(etu)

        return error_response(200, "OK")

    return error_response(409, "La requête ne peut être traitée en l’état actuel")


############################################### Departements ##########################################################


@bp.route("/test_liste_etudiants")
def test_departements_liste_etudiants():
    """
    Test la route liste_etudiants
    """
    # Set un département et un formsemestre pour les tests
    get_departement()
    get_formsemestre()

    global DEPT
    global FORMSEMESTRE

    # Set les fields à vérifier
    fields = [
        "civilite",
        "code_ine",
        "code_nip",
        "date_naissance",
        "email",
        "emailperso",
        "etudid",
        "nom",
        "prenom",
    ]

    # liste_etudiants (sans formsemestre)
    r1 = requests.get(
        SCODOC_URL + "/ScoDoc/api/departements/" + DEPT["acronym"] + "/etudiants/liste",
        auth=(SCODOC_USER, SCODOC_PASSWORD),
    )

    if r1.status_code == 200:  # Si la requête est "OK"
        # On récupère la liste des étudiants
        etudiants = r1.json()

        # Vérification que tous les étudiants ont bien tous les bons champs
        for etu in etudiants:
            for field in etu:
                if field not in fields:
                    return error_response(501, field + " field missing")

    # liste_etudiants (avec formsemestre)
    r2 = requests.get(
        SCODOC_URL
        + "/ScoDoc/api/departements/"
        + DEPT["acronym"]
        + "/etudiants/liste/"
        + str(FORMSEMESTRE["formsemestre_id"]),
        auth=(SCODOC_USER, SCODOC_PASSWORD),
    )

    if r2.status_code == 200:  # Si la requête est "OK"
        # On récupère la liste des étudiants
        etudiants = r2.json()

        # Vérification que tous les étudiants ont bien tous les bons champs
        for etu in etudiants:
            for field in etu:
                if field not in fields:
                    return error_response(501, field + " field missing")

        return error_response(200, "OK")

    return error_response(409, "La requête ne peut être traitée en l’état actuel")


@bp.route("/test_referenciel_competences")
def test_departements_referenciel_competences():
    """
    Test la route referenciel_competences
    """
    get_departement()
    get_formsemestre()

    global DEPT
    global FORMSEMESTRE

    # referenciel_competences
    r = requests.post(
        SCODOC_URL
        + "/ScoDoc/api/departements/"
        + DEPT["acronym"]
        + "/formations/"
        + FORMSEMESTRE["formation_id"]
        + "/referentiel_competences",
        auth=(SCODOC_USER, SCODOC_PASSWORD),
    )


@bp.route("/test_liste_semestre_index")
def test_departements_semestre_index():
    """
    Test la route semestre_index
    """
    # semestre_index
    r5 = requests.post(
        SCODOC_URL
        + "/ScoDoc/api/departements/"
        + DEPT["acronym"]
        + "/formsemestre/"
        + FORMSEMESTRE["formation_id"]
        + "/programme",
        auth=(SCODOC_USER, SCODOC_PASSWORD),
    )


#################################################### Etudiants ########################################################


def test_routes_etudiants():
    """
    Test les routes de la partie Etudiants
    """
    # etudiants
    r1 = requests.get(
        SCODOC_URL + "/ScoDoc/api/etudiants", auth=(SCODOC_USER, SCODOC_PASSWORD)
    )

    # etudiants_courant
    r2 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # etudiant
    r3 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # etudiant_formsemestres
    r4 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # etudiant_bulletin_semestre
    r5 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # etudiant_groups
    r6 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))


def test_routes_formation():
    """
    Test les routes de la partie Formation
    """
    # formations
    r1 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # formations_by_id
    r2 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # formation_export_by_formation_id
    r3 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # formsemestre_apo
    r4 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # moduleimpls
    r5 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # moduleimpls_sem
    r6 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))


def test_routes_formsemestres():
    """
    Test les routes de la partie Formsemestres
    """
    # formsemestre
    r1 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # etudiant_bulletin
    r2 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # bulletins
    r3 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # jury
    r4 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))


def test_routes_partitions():
    """
    Test les routes de la partie Partitions
    """
    # partition
    r1 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # etud_in_group
    r2 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # set_groups
    r3 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))


def test_routes_evaluations():
    """
    Test les routes de la partie Evaluations
    """
    # evaluations
    r1 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # evaluation_notes
    r2 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # evaluation_set_notes
    r3 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))


def test_routes_jury():
    """
    Test les routes de la partie Jury
    """
    # jury_preparation
    r1 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # jury_decisions
    r2 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # set_decision_jury
    r3 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # annule_decision_jury
    r4 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))


def test_routes_absences():
    """
    Test les routes de la partie Absences
    """
    # absences
    r1 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # absences_justify
    r2 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # abs_signale
    r3 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # abs_annule
    r4 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # abs_annule_justif
    r5 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # abs_groupe_etat
    r6 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))


def test_routes_logos():
    """
    Test les routes de la partie Logos
    """
    # liste_logos
    r1 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # recup_logo_global
    r2 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # logo_dept
    r3 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))

    # recup_logo_dept_global
    r4 = requests.post(SCODOC_URL + "/ScoDoc/api", auth=(SCODOC_USER, SCODOC_PASSWORD))
