#! python3
# -*- encoding: utf-8 -*-
'''
@File    :   myconfig.py
@Time    :   2023/03/01 15:28:20
@Author  :   Jim @ Yiwin 
@Version :   1.0
@Contact :   jim@yi-win.com
@Descrip :   SysConfig
'''

import yaml
from enum import Enum
from pathlib import Path
VERSION     = "3.3.5"
LASTDATE    = "2023-03-09"
COMPANY    = u"奕枫仪器"

DEVICE_ID = [2]
CURRENT_DIR = Path()
DATA_DIR = Path("data")
CAL_DIR = Path("calfile")
OUTPUT_DIR = Path("data", "output")
YAML_FILE_NAME = "config.yml"
RETRIEVE_CFG_FILE = "retrieve.yml"
FILE_MARK = ['Spectrum', 'DATA']
BEGIN_WAVELENGTH = 350
END_WAVELENGTH = 950
SAVE_EXT_NAME = ".csv"
INTERVAL = 1.0
SEPARATOR = ";"
TOKEN = ";"
NEWLINE = "\n"
ROWFACTOR = 0.026

class DeviceType(Enum) :
    AWRAMS      = 1
    SURFACE     = 2
    PROFILE     = 3

class RamsesFunc(Enum):
    Lsky        =   1
    Esky        =   2
    Lwater      =   3
    Lw          =   4
    Rs          =   5

class RamsesAWRAMS(Enum):
    Lsky        =   1
    Esky        =   2
    Lwater      =   3
    Lw          =   4
    Rs          =   5

class RamsesSURFACE(Enum):
    Lsky        =   1
    Esky        =   2
    Lwater      =   3
    Lw          =   4
    Rs          =   5
    
class RamsesPROFILE(Enum):
    Ed      =   1
    Esky    =   2
    Lu      =   3   #upwelling
    Lw          =   4
    Rs          =   5

IP_CAL = {
    "Incl_Orientation": "up",
    "Incl_Xgain": 1.0,
    "Incl_Xoffset": 125,
    "Incl_Ygain": 0.9375,
    "Incl_Yoffset": 126,
    "Incl_KBG": 1.2073,
    "Incl_Kref": 0.1275,
    "Press_Current_mA": 1.08,
    "Press_Surface_bar": 5.57,
    "Press_Gain": 2.7,
    "WithIncl": 1,
    "WithPress": 1,
    "Press_Sens_mV_bar_4mA": 71.36,
    "Press_Sens_mV_bar_1mA": 17.84,
    "Press_Type": "PA-10/TAB/10bar",
    "CalibrationDate": "08.06.2018",
}

RAMSES_CAL = {
            "SN": "",
            "TYPE": "SAM",  # SAMIP or SAM
            "FUNC": "Lsky",
            "inifile": "",
            "calfile": "",
            "calaqfile": "",
            "backfile": "",
            "samsn": "",
            "b0": [],
            "b1": [],
            "cal": [],
            "calaq": [],
            "DarkPixelStart": 237,
            "DarkPixelStop": 254,
            "Firmware": 2.06,
            "IDDataBack": "DLAB_2016-11-29_14-47-59_729_812",
            "IDDataCal": "DLAB_2016-12-07_12-00-24_364_510",
            "IDDataCalAQ": "DLAB_2016-12-07_12-02-43_591_545",
            "IntegrationTime": 0,
            "Reverse": 0,
            "SerialNo_MMS": 103307,
            "WavelengthRange": "310..1100",
            "c0s": 299.895,
            "c1s": 3.31161,
            "c2s": 0.00031652,
            "c3s": -1.73194e-06,
            "c4s": +0.000000000E+00,
            "cs": 102842,
            "savefile": ""
}

class MyConfig(object):
    """
    设置 ID对应的传感器
    """

    def __init__(self) -> None:
        self.device_id      = []
        self.device_type    = None
        self.current_device_id      = None
        self.system_cfg = {}
        self.cfg_path = Path()
        self.yml_cfg_file = YAML_FILE_NAME
        self.retrieve_cfg_file = Path(RETRIEVE_CFG_FILE)
        self.system_cal_cfg = {}
        self.validate = {    }

    def addDeviceID(self, id:int) -> None:  #
        self.device_id.append(id)
        pass
 
    def setDeviceID(self, id:int) -> bool:  # 
        if id in self.device_id:
            self.current_device_id = id
            return True
        else:
            self.current_device_id = None
            return False
        pass
       
    def setDeviceType(self, device_type:DeviceType) -> None:
        self.device_type = device_type
        pass   
 
    def setRetrieveCfg(self, rtv_yml:str="") -> None:
        if rtv_yml =="":
            return None
        self.retrieve_cfg_file = Path(rtv_yml)
        pass 
        
    def getSystemCfg(self,)->None:
        '''
        不同系统，修改此函数，或添加函数 getSystemCfg***()供调用
        '''
        if self.current_device_id == None:
            self.system_cfg = None
        if self.device_type == None:
            self.system_cfg = None
        temp_cfg = {}
        if self.device_type == DeviceType.AWRAMS:
            temp_cfg =  { 
                1: {"SN": "85B5", "FUNC": RamsesAWRAMS(1).name},
                2: {"SN": "50ED", "FUNC": RamsesAWRAMS(2).name},
                3: {"SN": "852F", "FUNC": RamsesAWRAMS(3).name}
            }
        if self.device_type == DeviceType.SURFACE:
            temp_cfg =  { 
                1: {"SN": "85B5", "FUNC": RamsesSURFACE(1).name},
                2: {"SN": "50ED", "FUNC": RamsesSURFACE(2).name},
                3: {"SN": "852F", "FUNC": RamsesSURFACE(3).name}
            }
        if self.device_type == DeviceType.PROFILE:
            temp_cfg =  { 
                1: {"SN": "85B5", "FUNC": RamsesPROFILE(1).name},
                2: {"SN": "50ED", "FUNC": RamsesPROFILE(2).name},
                3: {"SN": "852F", "FUNC": RamsesPROFILE(3).name}
            }
        self.system_cfg.update( { self.current_device_id : temp_cfg } )
        pass 

    def setCfgRamsesSN(self, sn_cfg: dict)->None:
        if len(sn_cfg) == 0:
            return None
        
        for k in self.system_cfg[self.current_device_id].keys():
            if str(k) in sn_cfg.keys() :
                self.system_cfg[self.current_device_id][k]["SN"] = sn_cfg[str(k)]
            else:
                self.system_cfg[self.current_device_id][k]["SN"] = None        
            # if  k  in sn_cfg.keys() :
            #     self.system_cfg[self.current_device_id][k]["SN"] = sn_cfg[k]
            pass

    def setSystemCalCfg(self, sn_cfg: dict)->None:
        if len(sn_cfg) == 0:    
            pass
        
    def getDictByAttr(self, *args) -> dict:
        ret = {}
        if len(args) == 0:
            return ret
        if len(args) == 1:
            if not hasattr(self, args[0]):
                return ret
            tmp = getattr(self, args[0])
            if isinstance(tmp, dict):
                ret.update(tmp)
            return ret
        if len(args) == 2:
            if not hasattr(self, args[0]):
                return ret
            if not isinstance(getattr(self, args[0]), dict):
                return ret
            tmp: dict = getattr(self, args[0])
            if not tmp.__contains__(args[1]):
                # print(f"------------{args[1]}")
                return ret
            tmp2 = tmp[args[1]]
            if isinstance(tmp2, dict):
                ret.update(tmp2)
            return ret
        if len(args) > 2:
            return ret
        pass

    # 设置字典对应的键值
    def set_attr(self, d: dict, k, v) -> bool: 
        if d.__contains__(k):
            d.update({k: v})
            return True
        return False

    def write_yaml(self,  d: dict):
        with open(self.yml_cfg_file, "w", encoding="utf-8") as f:
            yaml.dump(d, f)

    def read_yaml(self ) -> dict:
        with open(self.yml_cfg_file, "r", encoding="utf-8") as f:
            content = f.read()  # conent 读出来是字符串
            d = yaml.load(content, Loader=yaml.FullLoader)  # 用load方法转字典
        return d

    def write_rtv_yaml(self,  d: dict):
        with open(self.retrieve_cfg_file, "w", encoding="utf-8") as f:
            yaml.dump(d, f)

    def read_rtv_yaml(self ) -> dict:
        with open(self.retrieve_cfg_file, "r", encoding="utf-8") as f:
            content = f.read()  # conent 读出来是字符串
            d = yaml.load(content, Loader=yaml.FullLoader)  # 用load方法转字典
        return d

    def get_retrieve(self) -> dict:
        retrieve = {}
        retrieve.update({"beginWL": BEGIN_WAVELENGTH})
        retrieve.update({"endWL": END_WAVELENGTH})
        retrieve.update({"interval": INTERVAL})
        retrieve.update({"rowFactor": ROWFACTOR})
        return retrieve
        pass

ramses_buf_str= "\
    23a0000007fefe0a0781067d067d068e0693069c069c06b006b506cb06e40619076607e1076c081509cd09bb0a7d0bee0b1d0c6d0cca0ca40ddc0f30135b18b4224d320e43f852c8\
    23a0000006fefe17639c71c97c9484bb89358be98e5d98b1a37eadccb66abd26be31b97db124aa18a3f29c0499349735968e93a48eea8a028bc28cec8d048f1c92c096de9ab99d43\
    23a0000005fefee0a157a9ecb1b1b97dc034c507c741c7d2c65ec550c20dbde9b535ae56a60a9e2296cd8ee887278129798170c669b16503632e61605f3a5def5a8e5862561154be\
    23a0000004fefe3c51f54dda4a0c48634595426a3f5a3cc539903767362b36cc351f356634b633fc32c4310630fb2ec32fe63199349037e03ac03dc03eae3c303a9639d13a413da7\
    23a0000003fefe97412746bc49404caa4dc54d374ca646d63bde326b332739e43c503d2b3c363aca37ef342d32c22f782d1d2bd328ec250222101e691b2b1a7119d3184018fa174d\
    23a0000002fefed3177a17e3160616f81423149313f11233126711d8103b10a40f160f8a0efb0d580d660c6f0bd80aa10a580a000ab4099b0994097109e2082c087a0736072c077d\
    23a0000001fefe2a071e071607140718071e073c074d076a076e076b076007670763076c0760075c073d07350724071207fb06ef06d706cc06b706a506960684067b0672066306a2\
    23a0000000fefe58065406500642064e064306470642063f064806410644064306430641064206460640063c063e063e063d064406430644063c063c063c063c06400640064906ed\
    23a0000007fefe0a071b071c07260737073e0749075907650774078b07c0072c08e3082b0ada0be80d9c107b147318931ae51add1a271a77192f1bfb1d99207c265c30c738f03d53\
    23a0000006fefe07438f489d4d8452d957945cff639171a5832a97deab7fbe09c86cc5acb9d5ab299e90915287de7f8b7ae275ed6f056aff664f662665bc63936335655767926879\
    23a0000005fefec269206d3e724377fe7b7a8050831f85b68637881689e4884787008580823d7f887bee773d7496702a6cde654c5f895a1f570d5416514d4e9d4bde4897468c44c3\
    23a0000004fefe71421640db3dc83bbb39533777346c31b92e912c152b5b2aff292129e727cb26d925fd249223b4214020da1fe91ff41f28209420dc201520071e671c221c8d1cfe\
    23a0000003fefecd1dd31fe72164235924cb24b924f72331211e1ca018ef19221d121f621fe91e081ed51c761b311a2f193c18651788166015a013de11d1106e1041101810e80f2e\
    23a0000002fefee50fd90fbc0f6d0ff70e610ee00d930d460de40c900c450c010cbd0b7c0b480bfc0aab0a2c0a9e094d092b09fb08d008a208990881087d083908e6078d07660747\
    23a0000001fefe5b075a07500751074d074e0751075d076807730788077e077c077c07810777077a076c0765075c075607480740073607270723070d070d070b07ff06fd06f0062f\
    23a0000000fefef606f106ed06f506ef06eb06f106ec06f006e906e806ed06e606ef06e506ea06ec06ee06eb06e906ee06f006ef06ea06e906e606e606e606ec06ea06ea06f506f2\
    23a0000007fefe0605830479047d047e04810482048204850487048b048c04850487048c049304950498049c04a804a904b604b804c604d004e104f104190546059805ff059a06bb\
    23a0000006fefe90073209ea0b7610c117cc22b2324a487b645e8798acf2c927d28dc1f2a1ac809664804e543d7a308327a321d81dab1b0f1bca1bb41dba2098243329382e773335\
    23a0000005fefeca38213e544329486f4c1c500653335592564f577d573b57a556b4557e540a534451424f004d714a9b47994458410e3e9c3af8368c33b630982eca2c052b3429ae\
    23a0000004fefe632763255a234821321f0e1d061b291983171e16d814a91379124b1138104b0f610e990dd80c240c880bfc0a7b0af8097709020990082508de07c507ba07a50762\
    23a0000003fefe950781076407460727070007d306ab066e06270605060d0614061306fe05e805d105b405a00586057105630549053d0528051105fd04f304ee04e404dc04dd04c3\
    23a0000002fefed804d904d004c604bf04b904b904b104a804a604a6049d04980496048f04970491048c04880486047e0484047a047d047b047c0478047a04760476047004700430\
    23a0000001fefe6f0474046c046d0472046d047304750470046e04760472046f047604700473046f04730470047504700470046d046b047004710470046e046d046a046b046904e4\
    23a0000000fefe690470046e046b046c04680468046e0466046a046a0469046b046d04640466046c046c046b046a04660466046b046c046a046a0468046f046804740471048d0417\
    "

    
if __name__ == "__main__":
    s = RamsesPROFILE
    print(s(1))
    print(s(2))
    
    cfg = MyConfig()
    cfg.addDeviceID(2)
    cfg.addDeviceID(3)
    cfg.setDeviceType(DeviceType.AWRAMS)
    cfg.setDeviceID(2)
    cfg.getSystemCfg()
    print(cfg.system_cfg)
    
    d = {"1":"8888","2":["7777"],"3":["9999"]}
    cfg.setCfgRamsesSN(d)
    print("修改后。。。。。\n")
    print(cfg.system_cfg)
    
    # cfg.write_yaml( cfg.system_cfg)
    
    dd  = cfg.read_yaml()
    # dd 作为cfg.system_cfg 使用
    for k,v in dd.items():
        print(k)
        print(type(k))
    
    retrieve = {
        "beginWL": 350,
        "endWL": 950,
        "interval": 1,
        "rowFactor": 0.026
    }
