import os
import Manyo.Utsusemi as mu

class SetESiniFile:
    def __init__(self,ESinifile):
        if os.path.exists(ESinifile):
            self.ESinifile = ESinifile
        else:
            self.ESinifile = os.path.join(mu.UtsusemiEnvGetInstDir(),"ana","ElasticScanGUI",ESinifile)
        self.readESinifiles()
        self.commentheader = "ESGUIBase -->"
    def readESinifiles(self):
        f = open(self.ESinifile)
        _lines = f.readlines()
        f.close()
        
        self.ESini = {}
        for line in _lines:
            tt = line.split()
            if tt[0][0] != "#":
                self.ESini.update({tt[0]:tt[1]})
    
    def setparams(self,paramname,paramvalue):
        print(paramname, paramvalue)
        if paramname in self.ESini:
            self.ESini[paramname] = paramvalue
            print ("SetESiniFile -->", paramname, "is set as ", self.ESini[paramname],".")
        else:
            print ("SetESiniFile -->", paramname, "is not found in ", self.ESinifile,".")
            self.ESini.update({paramname: paramvalue})
            print ("SetESiniFIle -->", paramname, "is added as ", self.ESini[paramname], ".")


    def writeESinifiles(self):
        _savestring = "#generated by SetESiniFile\n"
        for k, v in self.ESini.items():
            _savestring += "%s  %s\n" %(k, v)
        
        _filename = "ESGUIParams.ini"
        f = open(_filename,"w")
        f.write(_savestring)
        f.close
        
        cwdpath = os.getcwd()+"/"+_filename
        #inipath = "/home/dnaadmin/ana/DNA/setup/"+_filename
        inipath = os.path.join(mu.UtsusemiEnvGetUserDir(), "ana", "DNA", "setup", _filename)
        if os.path.exists(inipath):
            os.remove(inipath)
            print (self.commentheader, "inifile:", cwdpath, " is removed")
        os.symlink(cwdpath,inipath)
        print (self.commentheader, "inifile:", cwdpath, " is updated")
        
