import os,sys,time
ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree
else:
    from xml.etree.ElementTree import ElementTree

class AnaEnviron(object):
    def __init__(self,envFile=""):
        self.CommentHead = "AnaEnviron >>> "
        if envFile=="":
            ret = -1
        else:
            self.envFile=envFile
            ret=self.loadEnvFile(self.envFile)
            if ret!=-1:
                self._anaEnvFile()
        
        self.Status = ret

    def loadEnvFile(self,envFile=""):
        if envFile=="" and self.envFile=="":
            print self.CommentHead+"File name is required."
            return -1
        if envFile!="":
            self.envFile=envFile
        
        envFilePath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",self.envFile)
        if os.path.exists(envFilePath):
            fd = file(envFilePath,'rb')
            self.dom=ElementTree(file=fd)
            fd.close()
            return 0
        else:
            print self.CommentHead+"Can not read file :"+envFilePath
            self.envFile=""
            return -1
    
    def _anaEnvFile(self):
        # Common Info
        self.Info={}
        root_ele = self.dom.getroot()
        ana_ele = root_ele.find("analysis")
        self.Info["InstCode"] = ana_ele.find("instcode").text
        self.Info["OrgWiringFile"] = ana_ele.find("originwiringfile").text
        self.Info["PositioningFile"] = ana_ele.find("positioningfile").text
        self.Info["FileHistory"] = []
        hist_ele = ana_ele.find("infofilehistory")
        if hist_ele!=None:
            period_list = hist_ele.findall("period")
            for a_period in period_list:
                st_run = int( a_period.attrib["startrun"] )
                ed_run = int( a_period.attrib["endrun"] )
                
                anamode_list = a_period.findall("params")
                if len(anamode_list)==0:
                    wfile_ele = a_period.find("wiringinfo")
                    dfile_ele = a_period.find("detectorinfo")
                    self.Info["FileHistory"].append( [st_run,ed_run,wfile_ele.text,dfile_ele.text] )
                else:
                    for a_param in anamode_list:
                        if a_param.attrib["mode"]=="0":
                            wfile_ele = anamode_list[0].find("wiringinfo")
                            dfile_ele = a_param.find("detectorinfo")
                            self.Info["FileHistory"].append( [st_run,ed_run,wfile_ele.text,dfile_ele.text] )
                            break
        
        # Single mode Info
        single_mode = ana_ele.find("singleload")
        single_p = single_mode.find("process")
        p = ProcessInfo(single_p)
        self.Info["SingleMode"] = p
        
        
class ProcessInfo(object):
    """
    This class is used to stock the information of each process
    Key of Dictionary in Info
        port         : port no
        multh        : if use multi-thread, set to 1
        wiringfile   : Wiring File name
        nexusFileExt : NeXusFile name to be saved on shared directory
    """
    def __init__(self,process_ele):
        self.CommentHead = "AnaEnviron.ProcessInfo >>>"
        self.Info = {}
        self._loadXml(process_ele)

    def _loadXml(self,process_ele):
        self.Info["port"] = int( process_ele.find("port").text )
        thread = process_ele.find("thread").text
        if thread=="single":
            self.Info["multh"] = False
        elif thread=="multi":
            self.Info["multh"] = True
        else:
            print self.CommentHead+"Warning:Thread tag context is invalid..(single/multh)",self.Info["port"]
            print self.CommentHead+"Warning:Using single thread."
            self.Info["multh"] = 0
                
        self.Info["wiringfile"] = process_ele.find("wiringfile").text
        module_list=[]
        for module_ele in process_ele.findall("moduleregion"):
            daq = int( module_ele.find("daq").text )
            mod_s = module_ele.find("module").text
            if type(mod_s)==type(""):
                mod_slist = mod_s.split(",")
            else:
                mod_slist = ["0"]
            for mod in mod_slist:
                module_list.append( (daq, int(mod)) )
        self.Info["modulelist"] = module_list
        if process_ele.find("outputoption") is not None:
            self.Info["nexusFileExt"] = process_ele.find("outputoption").text
        
        
