import utmpaccess
from UTMPCONST import *

class UtmpRecord:

    def __init__(self, fname=None):
        if fname:
            utmpaccess.utmpname(fname)
        self.setutent()
        
    def _makedict(self, a):
        if not a:
            return {}
        dict = {"ut_type": a[0],
                "ut_pid" : a[1],
                "ut_line": a[2],
                "ut_id"  : a[3],
                "ut_user": a[4],
                "ut_host": a[5],
                "ut_exit": a[6],
                "ut_session": a[7],
                "ut_tv" : a[8],
                "ut_addr_v6": a[9]
                }
        return dict
        
    def setutent(self):
        utmpaccess.setutent()
        
    def endutent(self):
        utmpaccess.endutent()

    def getutent(self):
        return utmpaccess.getutent()

    def getutent_dict(self):
        return self._makedict(self.getutent())
                
    def pututline(self, *ut):
        if len(ut) == 1:  # one tuple passed as argument
            apply(utmpaccess.pututline, ut[0])
        else:
            apply(utmpaccess.pututline, ut)
            
    def pututline_dict(self, ut_dict):
        self.pututline(
                        ut_dict['ut_type'],
                        ut_dict['ut_pid'],
                        ut_dict['ut_line'],
                        ut_dict['ut_id'],
                        ut_dict['ut_user'],
                        ut_dict['ut_host'],
                        ut_dict['ut_exit'],
                        ut_dict['ut_session'],
                        ut_dict['ut_tv'],
                        ut_dict['ut_addr_v6']
                        )
                       
    def getutid(self, ut_type, ut_id=''):
        return utmpaccess.getutid(ut_type, ut_id)

    def getutid_dict(self, ut_type, ut_id=''):
        return self._makedict(self.getutid(ut_type, ut_id))

    def getutline(self, ut_line):
        return utmpaccess.getutline(ut_line)

    def getutline_dict(self, ut_line):
        return self._makedict(self.getutline(ut_line))
        
    def __del__(self):
        self.endutent()
        
        