from ics2json import convert_url
from typing import List, Tuple, Dict, Any
import yaml


class CalMan:
    def __init__(self, conf_path: str) -> None:
        with open("config.yaml", "r") as f:
            self.config = yaml.load(f)

            self.tokens: Dict[str, int] = {}
            for g in self.config["groups"]:
                self.tokens[g["token"]] = g["id"]

            self.cals: Dict[str, Dict[str, Any]] = {}
            for c in self.config["cals"]:
                c["events"] = []
                self.cals[c["id"]] = c

    def list_group(self, group_id: int) -> List[Dict[str, str]]:
        l = []
        for c in self.config["cals"]:
            if group_id in c["groups"]:
                l.append({"label": c["title"], "label_id": c["id"]})
        return l

    def load_cal(self, cal_id: str) -> List[Any]:
        cal = self.cals[cal_id]
        events = cal["events"]

        if not events:
            events = convert_url(cal)
            self.cals[cal_id]["events"] = events

        return events

    def load_cal_group(self, group_id: str) -> List[Any]:
        events = []

        for cal_id in [c["label_id"] for c in self.list_group(group_id)]:
            events.extend(self.load_cal(cal_id))

        return events