#!/usr/bin/python 

import xmlrpclib
import socket
import sys
import os
import time
import stat

ServerExec  = 'perl /usr/local/bin/vulcan_server.pl'
PidDir      = '/tmp'
PidPrefix   = 'vulcan_'
PidSuffix   = '.pid'
PortRange   = range(13600,13800)

def get_next_port(port=None):
    """ return next pid number and pidfile for an unused connection"""

    def tryport(p,reuse=False):
        pidfile = os.path.join(PidDir,"%s%i%s" % (PidPrefix,p, PidSuffix))
        try:
            mtime = os.stat(pidfile)[stat.ST_MTIME]
        except OSError:  # file does not exst -- use this PID
            fx = open(pidfile,'w')
            return (p,pidfile)
        if reuse or (time.time() - mtime) > 1800:  # reuse old connection
            return (p,pidfile)
        return (None,None)

    # if an explicit port is requested, try that, even if we need to reuse one
    # (this is useful for debugging)
    if port is not None:
        return tryport(port,reuse=True)
        
    # if no port is specified, try the pool
    for p in PortRange:
        p,fpid = tryport(p)
        if p is not None: return (p,fpid)
        
    return (None,None) #  pool exhausted

def purge_connections(stale_age=7200,verbose=True):
    """ kill Vulcan Server processes and remove Pid files that are older than stale_age (in seconds)

    relies on linux/bsd-like  ps and kill system utilities.
    
    """
    purgefile = '/tmp/vulcan_purge.dat'
    pidcmd   = "ps -eo pid,args | grep 'perl'| grep '%%i' > %s 2>&1" % purgefile
    killcmd  = "kill -9 %i"

    if verbose:
        print 'Current Active Vulcan Ports'
        print 'Port     Time since last use (sec)'
    
    for fname in os.listdir(PidDir):
        if fname.startswith(PidPrefix) and fname.endswith(PidSuffix):
            modtime = os.stat(os.path.join(PidDir,fname))[stat.ST_MTIME]
            try:
                port = int(fname[len(PidPrefix):-4])
            except:
                if verbose:
                    print 'error getting port for file ', fname
                continue
            age = time.time()-modtime

            if verbose:
                print "  %i    %.2f" % (port, age)

            if age > stale_age:
                os.system(pidcmd % port)
                time.sleep(1.0)
                for i in open(purgefile).readlines():
                    try:
                        pid = int(i[:-1].strip().split()[0])
                        os.system(killcmd % pid)
                        os.unlink(os.path.join(PidDir,fname))
                    except:
                        if verbose:
                            print 'error with kill for pid/port ', pid, port
    try:
        os.unlink(purgefile)
    except OSError:
        pass

    
        
class VulcanClient:
    def __init__(self,host='localhost',port=None,purge=False):
        self.server = None
        self.kws = {}
        self.state_kws = {'element':None,'resource':None}
        self.available = None
        self.scattering = None

        if purge: purge_connections(verbose=False)
        
        self.port,self.pidfile = get_next_port(port=port)
        if self.port is None:
            raise IOError, 'No Ports available for VulcanServer'
        self.connect(host=host)
        
    def touch_pid(self):
        "touch pidfile, setting its modified time to now"
        if self.pidfile is not None:
            try:
                os.utime(self.pidfile,None)
            except OSError:
                pass
    
    def connect(self,host='localhost',spawn=True):
        "connect to a Vulcan Server, possibly spawning a new one."
        self.host = str(host)
        try:
            self.server = xmlrpclib.Server("http://%s:%i" % (self.host,self.port))
            self.rpcdata = self.server.available()
        except socket.error:
            print 'Starting Vulcan Server seems to not be running on port ', self.port
            self.server = None

            try:
                os.system('%s -p %i &' % (ServerExec, self.port))
                
                time.sleep(1.2)
                self.server = xmlrpclib.Server("http://%s:%i" % (self.host,self.port))
                self.rpcdata = self.server.available()
            except:
                
                print 'Cannot start Vulcan Server'
                self.server = None
                
        if self.server is not None:
            self.available = self.server.available()
            if 'None' in self.available: self.available.remove('None')

            self.scattering = self.server.scattering()
            if 'None' in self.scattering: self.scattering.remove('None')            

    def _prep(self,**kw):
        " prepare arguments for XML-RPC call"
        
        if self.server is None: self.connect()

        def _kwargs(**kw):  return kw

        args = _kwargs(**kw)
        for k,v in args.items():
            if v is None: args.pop(k)
        
        self.kws = args
        # use 'element' and 'resource' as "state keywords":
        # if explicitly set, use and save for next use.
        # if not set, look up and use saved value.
        for key in ('element','resource'):
            if self.kws.has_key(key):
                self.state_kws[key] = self.kws[key]
            elif self.state_kws[key] not in (None,''):
                self.kws[key] = self.state_kws[key]


        # before returning, touch pid file, signaling that this
        # port / pid are still in use
        self.touch_pid()

        return self.kws
    
    def has(self,element=None, **kw):
        """return True if element is in the current resource
        >>> x = VC.has(element='Mo', resource='McMaster')
        """        
        return (1 == self.server.has(self._prep(element=element,**kw)))

    def weight(self,element=None, **kw):
        """return elements weight
        >>>x = VC.weight(element='Mo')
        """
        return self.server.weight(self._prep(element=element, **kw))

    def density(self,element=None, **kw):
        """return elements density (most common form of pure element)
        >>>x = VC.density(element='Mo')
        """        
        return self.server.density(self._prep(element=element, **kw))

    def energy(self,element=None, **kw):
        """return energy in eV of an element's edge or emission line

        >>>x = VC.energy(element='Cu', edge='K')
        >>>x = VC.energy(element='Cu', line='Kalpha1')
        
        Edges are strings such as 'K', 'L3', 'M5', etc
        Lines can use Siegbahn ('Lbeta3'), shortened Siegbahn ('Lb3')
        or IUPAC ('L1-M3') notation.
        """
        return self.server.energy(self._prep(element=element, **kw))    



    def next_energy(self,element=None,edge=None,atoms=None,**kw):
        """ Given an element's edge and a list of atoms, returns the next highest
        edge that will be seen for that list of atoms.
        
        return (element, edge, energy) for the next edge (energy in eV)
        """
        if atoms is None or edge is None:
            print 'need an edge and list of atoms'
        self._prep(element=element,edge=edge,atoms= tuple(atoms), **kw)
        return tuple(self.server.next_energy(self.kws))

    def conversion(self,**kw):
        """Return the coeffient for converting cross-sections between barns to
        grams per square centimeter"""
        return self.server.conversion(self._prep(**kw))
    
    def siegbahn(self,**kw):
        """Return a line symbol in Siegbahn form.
        Input can be Siegbahn (Lbeta3), shortened Siegbahn (Lb3), or IUPAC (L1-M3).
        
        >>> print VC.siegbahn(line='lb3')
        Lbeta3
        """
        return self.server.siegbahn(self._prep(**kw))

    def iupac(self,**kw):
        """Return a line symbol in IUPAC form.
        Input can be Siegbahn (Lbeta3), shortened Siegbahn (Lb3), or IUPAC (L1-M3).
        
        >>> print VC.iupac(line='lb3')
        L1-M3
        """
        return self.server.iupac(self._prep(**kw))
    
    def gamma(self,element=None, edge=None, **kw):
        """Return an approximation of the core-hole lifetime for an element and edge.
        Data comes from K. Rahkonen and K. Krause, Atomic Data and Nuclear Data
        Tables, Vol 14, Number 2, 1974. 

        For O and P edges a value of 0.1 is returned

        Returns 0 for non-interpretable input
        """

        if edge is None: return None
        return self.server.gamma(self._prep(element=element, edge=edge, **kw))

    def fluor_yield(self,element=None, edge=None, **kw):
        """Return the fluorescence yield for an atomic symbol and edge
   
        fyield = VC.fluor_yield('Cu', edge='K')
        
        The value returned is the probability of an fluorescent x-ray being emitted
        for an absorption event.   
        Data comes from M. O. Krause, J. Phys. Chem. Ref. Data 8, 307 (1979)
        Returns -1 for non-interpretable input
        """

        if edge is None: return None
        return self.server.fluor_yield(self._prep(element=element, edge=edge, **kw))

    def edge_jump(self,element=None, edge=None, **kw):
        """Return edge jump ratio for an atomic symbol and edge

        jump = VC.edge_jump('Cu', edge='K')

        The value returned is the ratio of the above-edge absorption coefficient 
        to the below-edge coefficient
        """

        if edge is None: return None
        return self.server.edge_jump(self._prep(element=element, edge=edge, **kw))

    def intensity(self,element=None, line=None, **kw):
        """Return the intensity of the given emission line.  The
         intensities of all lines associated with a common core state sum to one.
         For example, the intensities of the 3 Kalpha and 5 Kbeta lines sum to one. 
        """

        if line is None:
            print 'need an line'
        return self.server.intensity(self._prep(element=element, line=line, **kw))

    
    def xsec(self,**kw):
        "total cross-section"
        return self.server.xsec(self._prep(**kw))

    def photo(self,**kw):
        "photo cross-section"
        return self.server.photo(self._prep(**kw))

    def coherent(self,**kw):
        "coherent cross-section"
        return self.server.coherent(self._prep(**kw))

    def incoherent(self,**kw):
        "incoherent cross-section"
        return self.server.incoherent(self._prep(**kw))

    def f1(self,resource='CL',**kw):
        "f' from CL "
        out =self.server.f1(self._prep(resource='CL',**kw))
        self.state_kws['resource'] = None
        return out

    def f2(self,resource='CL',**kw):
        "f'' from CL  "
        out =self.server.f2(self._prep(resource='CL',**kw))
        self.state_kws['resource'] = None
        return out

# $daemon -> dispatch_to(qw(has weight density conversion gamma
# 			  siegbahn iupac intensity
# 			  energy next_energy
# 			  xsec photo coherent incoherent f1 f2));

        

# print s.next_energy({'element': "Ti",'edge': "K",'atoms':['ba','ti','o']})        

if __name__ == '__main__':

    vc = VulcanClient(port=13702)
    print vc.available
    vc.has(element='Cu')
    print vc.weight()
    print vc.energy(edge='k')
    print vc.energy(line='kalpha1')
    print vc.energy(edge='k')
    print vc.gamma(edge='k')

    vc.has(element='Mo')
    print vc.weight()
    print vc.energy(edge='k')
    print vc.xsec(energies=[19994,20006])

#             

# 
# kws ={'element':"Cu", 'edge':'k'}
# 
# print s.has(element='Cu',edge='K')
# 
# print s.weight(kws), s.density(kws)
# 
# print s.energy({'element':'Cu', 'edge':'k'})
# print s.energy({'element':'Cu', 'line':'kalpha1'})
# 
# print "Core-hole lifetime of %(element)s K edge = " % kws,
# 
# print s.gamma(kws)
# 
# print s.next_energy({'element': "Ti",'edge': "K",'atoms':['ba','ti','o']})
# 

# print "elem Kalpha1 line = ", $rpcdata->result, $/;

# $rpcdata = $client -> iupac({line=>"lbeta3"});
# print "IUPAC notation for Lbeta3 = ", $rpcdata->result, $/;
# 
# 
# print $/;
# print "Elam total cross sections at 8700, 8800, 8900, 9000, 9100, 9200:\n";
# $rpcdata = $client -> xsec({element  => $elem,
# 			    energies => [8700, 8800, 8900, 9000, 9100, 9200]}
# 		      );
# print join(" ",@{ $rpcdata->result }), $/;
# 
# my $sum = 0;
# $rpcdata = $client -> intensity({element => $elem,
# 				 line    => "kalpha1"});
# print "$elem Kalpha1 intensity = ", $rpcdata->result, $/;
# $sum += $rpcdata->result;
# $rpcdata = $client -> intensity({element => $elem,
# 				 line    => "kalpha2"});
# print "$elem Kalpha2 intensity = ", $rpcdata->result, $/;
# $sum += $rpcdata->result;
# $rpcdata = $client -> intensity({element => $elem,
# 				 line    => "kalpha3"});
# print "$elem Kalpha3 intensity = ", $rpcdata->result, $/;
# $sum += $rpcdata->result;
# $rpcdata = $client -> intensity({element => $elem,
# 				 line    => "kb1"});
# print "$elem Kbeta1 intensity = ", $rpcdata->result, $/;
# $sum += $rpcdata->result;
# $rpcdata = $client -> intensity({element => $elem,
# 				 line    => "kb2"});
# print "$elem Kbeta2 intensity = ", $rpcdata->result, $/;
# $sum += $rpcdata->result;
# $rpcdata = $client -> intensity({element => $elem,
# 				 line    => "kb3"});
# print "$elem Kbeta3 intensity = ", $rpcdata->result, $/;
# $sum += $rpcdata->result;
# $rpcdata = $client -> intensity({element => $elem,
# 				 line    => "kb4"});
# print "$elem Kbeta4 intensity = ", $rpcdata->result, $/;
# $sum += $rpcdata->result;
# $rpcdata = $client -> intensity({element => $elem,
# 				 line    => "kb5"});
# print "$elem Kbeta5 intensity = ", $rpcdata->result, $/;
# $sum += $rpcdata->result;
# print $sum;
# 
# $rpcdata = $client -> incoherent({element  => $elem,
# 				  energies => [8700, 8800, 8900, 9000, 9100, 9200],
# 				  resource => "McMaster",
# 				 } );
# 
# print $/;
# print "McMaster incoherent cross sections at 8700, 8800, 8900, 9000, 9100, 9200:\n";
# print join(" ",@{ $rpcdata->result }), $/;
# 
# $rpcdata = $client -> intensity({element  => $elem,
# 				 line     => "kalpha1",
# 				 resource => "McMaster"});
# print "$elem Kalpha1 intensity = ", $rpcdata->result, $/;
# $rpcdata = $client -> intensity({element  => $elem,
# 				 line     => "kalpha2",
# 				 resource => "McMaster"});
# print "$elem Kalpha2 intensity = ", $rpcdata->result, $/;
# 
# 
# 
# $rpcdata = $client -> energy({element => "Ti",
# 			      edge    => "k"});
# print "\nTi K edge = ", $rpcdata->result, $/;
# print "next energy = ", join(" ", @{$rpcdata->result}), $/;
