from pathlib import Path

from .NoxAnnotationLoader import NoxAnnotationLoader
from pyPhasesRecordloader.recordLoaders.EDFRecordLoader import EDFRecordLoader
from pyPhasesRecordloader.recordLoaders.CSVMetaLoader import CSVMetaLoader


class RecordLoaderNox(EDFRecordLoader):
    def __init__(
        self,
        filePath=".",
        targetSignals=None,
        targetSignalTypes=None,
        optionalSignals=None,
        combineChannels=None,
    ) -> None:
        super().__init__(
            filePath,
            targetSignals,
            targetSignalTypes=targetSignalTypes,
            optionalSignals=optionalSignals,
            combineChannels=combineChannels,
        )

        self.exportsEventArray = True


    def loadAnnotation(self, recordId, fileName, valueMap=None):
        filePath = self.getFilePathAnnotation(recordId)
        annotationLoader = NoxAnnotationLoader.load(filePath, valueMap, self.annotationFrequency)

        return annotationLoader.events

    def getEventList(self, recordName, targetFrequency=1):
        metaXML = self.getFilePathAnnotation(recordName)
        xmlLoader = NoxAnnotationLoader()
        xmlLoader.startTime = self.startTime

        eventArray = xmlLoader.loadAnnotation(metaXML)
        self.lightOff = xmlLoader.lightOff
        self.lightOn = xmlLoader.lightOn

        if targetFrequency != 1:
            eventArray = self.updateFrequencyForEventList(eventArray, targetFrequency)

        return eventArray
    
    def getRelevantCols(self):
        return {
            "gender": lambda row: "male" if row["gender"] == 1 else "female",
            "age": "age_s1",
            "bmi": "bmi_s1",
            "tst": "slpprdp", # slptime in v.15
            "sLatency": "slplatp",
            "rLatency": "remlaiip",
            "waso": "waso",
            "sEfficiency": "slpeffp",
            "indexArousal": "ai_all",
            # countArousal
            "ArREMBP": "arrembp",
            "ArREMOP": "arremop",
            "ArNREMBP": "arnrembp",
            "ArNREMOP": "arnremop",
            "ahi": "ahi_a0h4a",
            "bp_diastolic": "diasbp",
            "bp_systolic": "systbp",
            "race": "race", 
            # % N1, N2, N3, R
            # therapy / diagnostics
            # Diagnosis
            # PLMSI
            # PLMSIArI
        }

    def getMetaData2(self, recordName, loadMetadataFromCSV=True):
        return self.metadataPath.replace("{recordId}", str(recordName))
    
    def getMetaData(self, recordName, loadMetadataFromCSV=True):
        metaData = super().getMetaData(recordName)
        metaData["recordId"] = recordName

        return metaData
    
    def getAllMetaData(self, visit=1):
        relevantCols = self.getRelevantCols()
        csvLoader = CSVMetaLoader(
            f"{self.filePath}/datasets/Nox{visit}-dataset-0.20.0.csv", idColumn="nsrrid", relevantRows=relevantCols
        )
        csvMetaData = csvLoader.getAllMetaData()
        csvMetaData["countArousal"] = csvMetaData["ArREMBP"] + csvMetaData["ArREMOP"] + csvMetaData["ArNREMBP"] + csvMetaData["ArNREMOP"]

        # append Nox1 to recordId
        csvMetaData["recordId"] = f"Nox{visit}-" + csvMetaData["recordId"].astype(str)

        return csvMetaData

    def getSubjectId(self, recordId):
        return recordId
    
    def getSessionId(self, recordId):
        return "1"
    
    
    # Compumedics P-series Sleep Monitoring system, version 3
    def getDICOMMetadata(self, recordId):
        return {
            "Manufacturer": "Nox Medical",
            "ManufacturerModelName": "Noxturnal",
            "DeviceSerialNumber": "",
            "SoftwareVersions": "",
        }