import glob, os
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
from django.shortcuts import render_to_response
from rlextra.ers.apploggers import AppLogEntry, FileAppLogger
from xml.sax.saxutils import escape

def entryListing(logFile, errorsOnly=False):
    "Returns listings from log file"
    links = []
    try:
        log = open(logFile, 'r').readlines()
    except:
        log = []
    for l in log:
        l = l.split()
        k = l[0]
        e = AppLogEntry()
        e.restore_from_string(''.join(l[1:]))
        user = e.getUsername()
        if user is not None: userDetails = ' (%s)' % user
        else: userDetails = ''
        try: action = e['startcgi']['action']
        except: action = None
        try: error = e['error']
        except: error = None
        if error:
            try:
                et = error.get('error_type','')
                ev = error.get('error_value','')
                from xml.sax.saxutils import escape
                if et or ev: ev = ' error=%s(%s)' % (et,escape(ev))
            except:
                ev = ''
            links.append('<a href="%s"><font color="red">id=%s action=%s%s</font></a>%s' % (k, k, action, ev, userDetails))
        else:
            if errorsOnly:
                continue
            i = links.append('<a href="%s">id=%s action=%s</a>%s' % (k,k,action, userDetails))
    links.reverse()
    links = '<h3>Recent Log Lists</h3>' + '<br/>'.join(links)
    return links

def viewLogs(request):
    "Django equivalent of html_logfiles_form in webapp"
    logger = FileAppLogger(logSourceDir=settings.LOG_ROOT, logSourceHostname=request.META['SERVER_NAME'], appName=settings.APPNAME)
    logs = logger.logfiles()
    log = ''
    if logs:
        log = request.POST.get('log', logs[0])
    d = {'title': 'View Log Files', 'user': request.user, 'os':os,
         'logs': logs, 'logger': logger, 'log':log, 'listing': entryListing(log),}
    return render_to_response('viewlog.html', d)

def retryForm(e):
    content = []
    content.append('<form action="%s" method="%s">' % (e['startcgi']['path'], e['startcgi']['requestMethod'].lower()))
    params = e['startcgi']['params']
    for p in params:
        content.append('<input type="hidden" name="%s" value="%s"/>' % (p, params[p][0]))
    content.append('<input type="submit" value="Retry this Entry"/>')
    content.append('</form>')
    return '\n'.join(content)

def viewLogEntry(request, id):
    logger = FileAppLogger(logSourceDir=settings.LOG_ROOT, appName=settings.APPNAME)
    logFN = id.split('-')[:-1]
    logFN[1] = settings.APPNAME
    logFN[2] = logFN[2][:8]
    logFN.append('log.txt')
    logFN = '-'.join(logFN)
    e = logger._getentry(id, os.path.join(settings.LOG_ROOT, logFN))
    username = e.getUsername()
    ftb = e.get('error', {})
    ftb = ftb.get('ftb', '')
    d = {'title': 'Log Entry', 'id': id, 'e':e, 'ftb': ftb, 'username': username, 'retryForm': retryForm(e), 'escape':escape}
    return render_to_response('viewentry.html', d)