from . import auth
from . import user

import requests

def get_grades_moment(login_method, *args, **kwargs):
    try:
        match login_method:
            case "access_token": 
                access_token = args[0]
            case "refresh_token":                
                returned_rt = auth.using_refresh_token(args[0])
                access_token = returned_rt["access_token"]
            case "uname_pword":
                if len(args) > 3: email = args[3]
                else: email = None
                returned_up = auth.using_uname_pword(args[0], args[1], args[2], email)
                access_token = returned_up["access_token"]
            case _:
                return "This login method does not exist."
    except IndexError as e:
        return "Somewhere there is this error."
    
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json",
        "Accept-Language": "en-US",
        "User-Agent": "Mozilla/5.0"
    }
    
    student_id = user.get_student_uuid("access_token", access_token)

    gradesMomentJson = requests.get(url=f"https://api.somtoday.nl/rest/v1/resultaatpublicatiemomenten/volgende/leerling/{student_id}", headers=headers)
    gradesMoment = gradesMomentJson.json().get("value")
    
    return gradesMoment

def get_grades_list(login_method, *args, **kwargs):
    try:
        match login_method:
            case "access_token": 
                access_token = args[0]
            case "refresh_token":                
                returned_rt = auth.using_refresh_token(args[0])
                access_token = returned_rt["access_token"]
            case "uname_pword":
                if len(args) > 3: email = args[3]
                else: email = None
                returned_up = auth.using_uname_pword(args[0], args[1], args[2], email)
                access_token = returned_up["access_token"]
            case _:
                return "This login method does not exist."
    except IndexError as e:
        return "Somewhere there is this error."
    
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json",
        "Accept-Language": "en-US",
        "User-Agent": "Mozilla/5.0"
    }
    
    student_id = user.get_student_uuid("access_token", access_token)

    gradesJson = requests.get(url=f"https://api.somtoday.nl/rest/v1/geldendvoortgangsdossierresultaten/leerling/{student_id}?type=Toetskolom&type=DeeltoetsKolom&type=Werkstukcijferkolom&type=Advieskolom&additional=vaknaam&additional=resultaatkolom&additional=naamalternatiefniveau&additional=vakuuid&additional=lichtinguuid&sort=desc-geldendResultaatCijferInvoer", headers=headers)
    grades = gradesJson.json().get("items")
    
    return grades

def get_grades_formatted(login_method, *args, **kwargs):
    grades = get_grades_list(login_method, *args, **kwargs)
    
    if not isinstance(grades, list):
        return grades

    grades_formatted = []

    for item in grades:
        if not item.get("isCijfer"):
            continue

        grades_formatted.append({
            "date": item.get("datumInvoerEerstePoging"),
            "subject": item.get("additionalObjects", {}).get("vaknaam"),
            "grade": item.get("cijfer"),
            "period": item.get("periode")
        })
        
    grades_formatted.sort(key=lambda x: x["date"], reverse=True)
    return grades_formatted

def get_grades_subjects(login_method, *args, **kwargs):
    grades = get_grades_formatted(login_method, *args, **kwargs)

    if not isinstance(grades, list):
        return grades

    grouped = {}

    for item in grades:
        subject = item["subject"]
        grade = item["grade"]

        if subject not in grouped:
            grouped[subject] = {
                "grades": [],
                "average": 0
            }

        grouped[subject]["grades"].append(grade)

    for subject, data in grouped.items():
        grades_list = data["grades"]
        avg = sum(grades_list) / len(grades_list)
        grouped[subject]["average"] = round(avg, 2)

    return grouped