
from datetime import datetime
from typing import List

from pyPhasesRecordloader import AnnotationInvalid, AnnotationNotFound, Event

# from pyPhasesRecordloader.recordLoaders.XMLAnnotationLoader import XMLAnnotationLoader
from pyPhasesRecordloader import RecordLoader

class NoxAnnotationLoader(RecordLoader):
    mapping = {
        # Sleep Staging
        "Wach": "W",
        "N1": "N1",
        "N2": "N2",
        "N3": "N3",
        "REM": "R",

        # Arousal
        "Arousal": "arousal",

        # Leg
        "LM": "LegMovement",
        "PLMS": "LegMovement",
        # "PLM": "LegMovement", # Full episode

        # Resp. Events        
        "Hypopnoe": "resp_hypopnea",
        "A. Zentral": "resp_centralapnea",
        "A. Gemischt": "resp_mixedapnea",
        "A. Obstruktiv": "resp_obstructiveapnea",
        "H. Obstruktiv": "resp_hypopnea_obstructive",
        "H. Zentral": "resp_hypopnea_central", # not actual seen
        "Rera": "arousal_rera",
    }
    # Others
    # 'Einzelnes Schnarchen',   
    # 'Normal',
    # 'Flusslimitation': '',
    # 'R?ckenlage': '',
    # 'Bewegung': '',
    # 'PWA-Abfall': '',
    # 'Ents?ttigung': '',
    # 'Rechts': '',   # vermutlich Position
    # "Links": "",
    # "Artefakt": "",
    # "Schnarchintervall": "",
    # "Paradoxe Atmung": "", Tachykardie


    def loadAnnotation(self, csvFile) -> List[Event]:
        import pandas as pd

        df = pd.read_csv(csvFile)

        allEvents = []
        # df columns Ereignis,Anfangszeit,Endzeit,Dauer,Start Zeitabschnitt,Ende Zeitabschnitt, _

        if self.startTime is None:
            raise Exception("before loading the annotation a start time needs to be specified!")

        for name, start_time_str, end, duration, _, _, _  in df.iloc:

            if name in self.mapping:
                dt = datetime.strptime(start_time_str, "%d.%m.%Y %H:%M:%S")

                event = Event(self.mapping[name], duration=float(duration))
                
                diff = dt - self.startTime
                event.start = int(diff.total_seconds())

        self.lightOff = 0
        self.lightOn = None

        return allEvents

    def fillRecord(self, record, xmlFile):
        pass
