#
# mkbackup/windows.py
#
# windows code


import time
#======================================================================
#
# Event Viewer logging
#
#======================================================================
import win32evtlog
import win32evtlogutil
import winerror
import win32con

evt_dict={
        win32con.EVENTLOG_AUDIT_FAILURE:'AUDIT_FAILURE',
        win32con.EVENTLOG_AUDIT_SUCCESS:'AUDIT_SUCCESS',
        win32con.EVENTLOG_INFORMATION_TYPE:'INF',
        win32con.EVENTLOG_WARNING_TYPE:'WAR',
        win32con.EVENTLOG_ERROR_TYPE:'ERR'
        }

# ---------------------------------------------------------------------
def FormatEv(ev_obj, logtype):
    computer=str(ev_obj.ComputerName)
    # cat=str(ev_obj.EventCategory)
    level=str(ev_obj.EventType )
    record=str(ev_obj.RecordNumber)
    evt_id=str(winerror.HRESULT_CODE(ev_obj.EventID))
    evt_type=evt_dict.get(ev_obj.EventType, 'UNK')
    msg=win32evtlogutil.SafeFormatMessage(ev_obj, logtype)
    epoch=int(ev_obj.TimeGenerated)
    msg=u'=== eventid=%d eventtype=%s epoch=%d time="%s" ===\r\n%s' % ( ev_obj.EventID, evt_type, epoch, time.ctime(epoch), msg)
    #print ev_obj.EventID, evt_type, int(ev_obj.TimeGenerated), level, msg.encode('UTF-8')
    return msg 

# ---------------------------------------------------------------------
def ReadEvLog(logtype, source, start, end=None):
    # If any event is not 'INFO' => return 'ERR'
    # If the last event is not an 'INFO' => return 'WAR' (in fact when not event are present)
    # Else return 'OK'
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    hand=win32evtlog.OpenEventLog(None, logtype) # None for localhost
    cont, output, status='first', u'', 'WAR'
    while cont:
        events=win32evtlog.ReadEventLog(hand,flags,0)
        for ev_obj in events:
            src=str(ev_obj.SourceName)
            if src!=source:
                break
            if int(ev_obj.TimeGenerated)<start:
                cont=False
                break
            if ev_obj.EventType!=win32con.EVENTLOG_INFORMATION_TYPE:
                status='ERR'

            if cont=='first':
                #print 'first %r %r %r %r' % (ev_obj.EventID=='8001', ev_obj.EventType==win32con.EVENTLOG_INFORMATION_TYPE, ev_obj.EventID, ev_obj.EventType)
                cont=True
                if ev_obj.EventID==8019 and ev_obj.EventType==win32con.EVENTLOG_INFORMATION_TYPE:
                    status='OK'
                
            if output:
                output=FormatEv(ev_obj, logtype)+u'\r\n'+output
            else:
                output=FormatEv(ev_obj, logtype)

        cont=cont and events
    win32evtlog.CloseEventLog(hand)
    return status, output

