from pathlib import Path, PurePath

from tools.mylogger import log
from readcal import ReadCal

from myconfig import CAL_DIR, DATA_DIR, FILE_MARK, DeviceType, RamsesFunc


class Configuration:
    def __init__(self, ) -> None:
        log.info(f"ConfigAWRAMS init:  ", __name__, "", "")
        self.device_type = None
        self.configuration =None
        self.cal_configuration = {}
        pass
    


    def setDeviceType(self, device_type:str) -> None:
        self.device_type = device_type.lower()
        pass

    def setSystemCfgDict(self, cfg:dict) -> None:
        self.configuration = cfg 
        log.info(f"self.configuration : {self.configuration} ", __name__, "", "")
        pass
    
    def getCalConfiguration(self) -> None:
        if self.device_type == None:
            self.cal_configuration = None
        if self.configuration == None:
            self.cal_configuration =None
        
        for k,v in self.configuration.items(): 
   
            if v["SN"] == "" or v['FUNC']=="":
                pass
            else:
                self.cal_configuration.update( {v["FUNC"]:{}} )
                self.cal_configuration[v["FUNC"]].update( {"SN":v['SN']} )          
                self.cal_configuration[v["FUNC"]].update( {"FUNC":v['FUNC']} )  
                    
            self.__init_configuration_basic()
            self.__init_configuration_cal()
            self.__init_configuration_IP_SAM()        
        pass

    def __init_configuration_basic(self ) -> None:
        # self.cfgtool = Config()
        for k  in self.cal_configuration.keys(): 
            sn = self.cal_configuration[k]["SN"]
            if self.__isSamIniExisted(sn):
                self.cal_configuration[k].update({   "TYPE" : "SAM" })
                self.cal_configuration[k].update({   "samsn" : sn })
                self.cal_configuration[k].update({   "inifile" : "SAM_"+sn+".ini" })
                self.cal_configuration[k].update({   "calfile" : "Cal_SAM_"+sn+".dat" })
                self.cal_configuration[k].update({   "calaqfile" : "CalAQ_SAM_"+sn+".dat" })
                self.cal_configuration[k].update({   "backfile" : "Back_SAM_"+sn+".dat" })
            if self.__isSamIPIniExisted(sn):
                self.cal_configuration[k].update({   "TYPE" : "SAMIP" })
                samsn = self.__getSAMSN(sn)
                if samsn== None:
                    log.warning(f"Cannot get samsn from Sensor:  {sn}", __name__, "", "" )
                    raise Exception(f"Cannot get samsn from Sensor:  {sn}")       
                self.cal_configuration[k].update({   "samsn" : samsn })
                self.cal_configuration[k].update({   "inifile" : "SAMIP_"+sn+"_ALL.ini" })
                self.cal_configuration[k].update({   "calfile" : "Cal_SAM_"+samsn+".dat" })
                self.cal_configuration[k].update({   "calaqfile" : "CalAQ_SAM_"+samsn+".dat" })
                self.cal_configuration[k].update({   "backfile" : "Back_SAM_"+samsn+".dat" })
            if not self.__isSamIniExisted(sn) and not self.__isSamIPIniExisted(sn):
                log.warning(f"Cannot find ini file for Sensor:  {sn}", __name__, "", "" )
                raise Exception(f"Cannot find ini file for Sensor:  {sn}") 

            pass    

    def __init_configuration_cal(self ) -> None:
        # self.cfgtool = Config()
        for k  in self.cal_configuration.keys(): 
            sn = self.cal_configuration[k]["SN"]
            # Device File
            calpath = CAL_DIR.joinpath(self.device_type,  self.cal_configuration[k]["calfile"])
            if calpath.exists(  ):
                res = ReadCal.read_columns_set_by_mark( calpath,  FILE_MARK, 1 )
                self.cal_configuration[k].update({   "cal" : res[1][0] })
            calaqpath = CAL_DIR.joinpath(self.device_type,  self.cal_configuration[k]["calaqfile"])
            if calaqpath.exists(  ):
                res = ReadCal.read_columns_set_by_mark( calaqpath,  FILE_MARK, 1 )
                self.cal_configuration[k].update({ "calaq" : res[1][0] })
            backpath = CAL_DIR.joinpath(self.device_type,  self.cal_configuration[k]["backfile"])
            if calaqpath.exists(  ):
                res = ReadCal.read_columns_set_by_mark( backpath,  FILE_MARK, 1,2 )
                self.cal_configuration[k].update({ "b0" : res[1][0] })
                self.cal_configuration[k].update({ "b1" : res[1][1] })
            pass



    def __init_configuration_IP_SAM(self ) -> None:
        # self.cfgtool = Config()
        for j  in self.cal_configuration.keys(): 
            # log.debug(f"__init_configuration_IP_SAM  {j}", __name__, "", "" )
            inipath = CAL_DIR.joinpath(self.device_type,  self.cal_configuration[j]["inifile"])
            # log.debug(f"__init_configuration_IP_SAM  {inipath}", __name__, "", "" )
            sam = ReadCal.readSAMCalFromIni(inipath)
            # log.debug(f"__init_configuration_IP_SAM  {sam}", __name__, "", "" )
            for k,v in sam.items(): 
                self.cal_configuration[j].update({ k : v })
            if self.cal_configuration[j]["TYPE"] ==  "SAMIP":
                ip = ReadCal.readIPCalFromIni(inipath)
                for k,v in ip.items(): 
                    self.cal_configuration[j].update({ k : v })          

    def __isSamIniExisted(self,sn) ->bool:
        sn_0 = "SAM_"+str(sn)+".ini"
        path_ = CAL_DIR.joinpath(self.device_type.lower(), sn_0)
        if path_.exists():
            return True
        return False
 

    def __isSamIPIniExisted(self,sn) ->bool:
        sn_0 = "SAMIP_"+str(sn)+"_ALL.ini"
        path_ = CAL_DIR.joinpath(self.device_type.lower(), sn_0)
        if path_.exists():
            return True
        return False

    def __getSAMSN(self,sn) -> None:
        sn_0  = "SAMIP_"+str(sn)+"_ALL.ini"
        path_ = CAL_DIR.joinpath(self.device_type.lower(), sn_0)
        # path_ = DATA_DIR.joinpath(self.device.lower(), CAL_DIR, sn_0)
        samsn = ReadCal.readSamSNFromIni( path_ )
        if samsn == None:
            return None
        return samsn
        pass

    # def __init2__(self, device:str, **kwargs) -> None:
    #     """   
    #     get cal parameter for every sensor
    #     para : {"1":{"SN":"85B5","FUNC","Lsky"},"2":{},"3":{}}
    #     """
    #     # log.info(f"ProcessAWRAMS kwargs:  {kwargs}", __name__, "", "")
    #     # log.info(f"len: { len(kwargs)}", __name__, "", "")

    #     if len(kwargs) != 3:
    #         log.warning(f" pass a wrong para to ProcessAWRAMS {kwargs}", __name__, "", "")
    #     self.device = device.lower()  # surface profile awrams
    #     self.ramses = {}
        
    #     # 生成标定文件 {  }
    #     for k,v in kwargs.items(): 
    #         self.ramses.update( {v["FUNC"]:{}} )
    #         self.ramses[v["FUNC"]].update( {"SN":v['SN']} )          
    #         self.ramses[v["FUNC"]].update( {"FUNC":v['FUNC']} )          
    #         pass
    #     log.debug(f" =====  {self.ramses}",__name__, "", "" )
        
           
    #     # if kwargs.__contains__("1"):
    #     #     self.ramses.append( self.cfgtool.getDictByAttr("ramses"))
    #     #     self.cfgtool.set_attr(self.ramses[1],kwargs['1']"SN",kwargs['1'])
    #     # if kwargs.__contains__("2"):
    #     #     self.ramses.append( self.cfgtool.getDictByAttr("ramses"))
    #     #     self.cfgtool.set_attr(self.ramses[2],"SN",kwargs['1'])
    #     # if kwargs.__contains__("3"):
    #     #     self.ramses.append( self.cfgtool.getDictByAttr("ramses"))
    #     #     self.cfgtool.set_attr(self.ramses[3],"SN",kwargs['1'])

    #     self.__init_configuration_basic()
    #     self.__init_configuration_cal()
    #     self.__init_configuration_IP_SAM()
        
    #     # log.info(f"ProcessAWRAMS after initiate:   {kwargs}", __name__, "", "")

    # def __init_configuration_basic2(self ) -> None:
    #     # self.cfgtool = Config()
    #     for k  in self.ramses.keys(): 
    #         sn = self.ramses[k]["SN"]
    #         if self.__isSamIniExisted(sn):
    #             self.ramses[k].update({   "TYPE" : "SAM" })
    #             self.ramses[k].update({   "samsn" : sn })
    #             self.ramses[k].update({   "inifile" : "SAM_"+sn+".ini" })
    #             self.ramses[k].update({   "calfile" : "Cal_SAM_"+sn+".dat" })
    #             self.ramses[k].update({   "calaqfile" : "CalAQ_SAM_"+sn+".dat" })
    #             self.ramses[k].update({   "backfile" : "Back_SAM_"+sn+".dat" })
    #         if self.__isSamIPIniExisted(sn):
    #             self.ramses[k].update({   "TYPE" : "SAMIP" })
    #             samsn = self.__getSAMSN(sn)
    #             if samsn== None:
    #                 log.warning(f"Cannot get samsn from Sensor:  {sn}", __name__, "", "" )
    #                 raise Exception(f"Cannot get samsn from Sensor:  {sn}")       
    #             self.ramses[k].update({   "samsn" : samsn })
    #             self.ramses[k].update({   "inifile" : "SAMIP_"+sn+"_ALL.ini" })
    #             self.ramses[k].update({   "calfile" : "Cal_SAM_"+samsn+".dat" })
    #             self.ramses[k].update({   "calaqfile" : "CalAQ_SAM_"+samsn+".dat" })
    #             self.ramses[k].update({   "backfile" : "Back_SAM_"+samsn+".dat" })
    #         if not self.__isSamIniExisted(sn) and not self.__isSamIPIniExisted(sn):
    #             log.warning(f"Cannot find ini file for Sensor:  {sn}", __name__, "", "" )
    #             raise Exception(f"Cannot find ini file for Sensor:  {sn}") 

    #         pass
    
    # def __init_configuration_cal2(self ) -> None:
    #     # self.cfgtool = Config()
    #     for k  in self.ramses.keys(): 
    #         sn = self.ramses[k]["SN"]
    #         # Device File
    #         calpath = CAL_DIR.joinpath(self.device,  self.ramses[k]["calfile"])
    #         if calpath.exists(  ):
    #             res = Readfile.read_columns_set_by_mark( calpath,  FILE_MARK, 1 )
    #             self.ramses[k].update({   "cal" : res[1][0] })
    #         calaqpath = CAL_DIR.joinpath(self.device,  self.ramses[k]["calaqfile"])
    #         if calaqpath.exists(  ):
    #             res = Readfile.read_columns_set_by_mark( calaqpath,  FILE_MARK, 1 )
    #             self.ramses[k].update({ "calaq" : res[1][0] })
    #         backpath = CAL_DIR.joinpath(self.device,  self.ramses[k]["backfile"])
    #         if calaqpath.exists(  ):
    #             res = Readfile.read_columns_set_by_mark( backpath,  FILE_MARK, 1,2 )
    #             self.ramses[k].update({ "b0" : res[1][0] })
    #             self.ramses[k].update({ "b1" : res[1][1] })
    #         pass
    
    # def __init_configuration_IP_SAM2(self ) -> None:
    #     # self.cfgtool = Config()
    #     for j  in self.ramses.keys(): 
    #         # log.debug(f"__init_configuration_IP_SAM  {j}", __name__, "", "" )
    #         inipath = CAL_DIR.joinpath(self.device,  self.ramses[j]["inifile"])
    #         # log.debug(f"__init_configuration_IP_SAM  {inipath}", __name__, "", "" )
    #         sam = Readfile.readSAMCalFromIni(inipath)
    #         # log.debug(f"__init_configuration_IP_SAM  {sam}", __name__, "", "" )
    #         for k,v in sam.items(): 
    #             self.ramses[j].update({ k : v })
    #         if self.ramses[j]["TYPE"] ==  "SAMIP":
    #             ip = Readfile.readIPCalFromIni(inipath)
    #             for k,v in ip.items(): 
    #                 self.ramses[j].update({ k : v })  