from pathlib import Path
from importlib import resources
import pandas as pd
import yaml


def load_map_resource():
    with resources.as_file(resources.files("pygpa").joinpath("map.yaml")) as p:
        return yaml.safe_load(p.read_text(encoding="utf-8"))


mappings = load_map_resource()


class Course:
    def __init__(
        self,
        title,
        credits,
        grade,
        mapping,
        weight=0,
    ):
        self.title = title
        self.credits = credits
        self.grade = grade
        self.mapping = mapping
        self.weight = weight

    def __str__(self):
        return f"{self.title} ({self.credits} cr.): {self.grade}"

    def qp(self):
        return self.credits * mappings[self.mapping][self.grade]

    def weighted_qp(self):
        return self.credits * (mappings[self.mapping][self.grade] + self.weight)


def parse(dataframe, mapping):
    course_list = []

    for index, row in dataframe.iterrows():
        course_list.append(
            Course(
                row["Title"],
                row["Credits"],
                row["Grade"],
                mapping,
                row["Weight"],
            )
        )

    return course_list


def unweighted(course_list):
    quality_points = 0
    cumulative_credits = 0

    for course in course_list:
        quality_points += course.qp()
        cumulative_credits += course.credits

    return quality_points / cumulative_credits


def weighted(course_list):
    quality_points = 0
    cumulative_credits = 0

    for course in course_list:
        quality_points += course.weighted_qp()
        cumulative_credits += course.credits

    return quality_points / cumulative_credits
