import random

from quixote import get_publisher, get_request, get_response, redirect
from quixote.directory import Directory

from larpe.qommon.form import *
from larpe.qommon import template

from qommon import logger
from larpe import misc
from larpe.users import User

from menu import *

class ByUserDirectory(Directory):
    def _q_lookup(self, component):
        return ByUserPages(component)


class LoggerDirectory(Directory):
    _q_exports = ['', 'download', 'by_user']

    by_user = ByUserDirectory()

    def _q_index [html] (self):
        get_response().breadcrumb.append( ('logger/', _('Logs')) )
        html_top('logger', title = _('Logs'))
        request = get_request()
        logfile = request.get_field('logfile', 'larpe.log')
        if not logfile.startswith(str('larpe.log')) or str('/') in str(logfile):
            return template.error_page(_('Bad log file: %s') % logfile)
        logfilename = str(os.path.join(get_publisher().app_dir, logfile))

        if not os.path.exists(logfilename):
            _('Nothing to show')
        else:
            if logfile:
                '<a href="download?logfile=%s">%s</a>' % (logfile, _('Download Raw Log File'))
            else:
                '<a href="download">%s</a>' % _('Download Raw Log File')

            user_color_keys = {}
            last_date = None
            '<table id="logs">\n'
            '<thead> <tr>'
            ' <th>%s</th>' % _('Time')
            ' <th>%s</th>' % _('User')
            ' <th>%s</th>' % _('Message')
            '<tr></thead>\n'
            '<tbody>\n'
            for line in open(logfilename):
                d = logger.readline(line)
                user_color_key = d['user_id']
                if user_color_key == 'anonymous':
                    user_color_key += d['ip']
                if not user_color_keys.has_key(user_color_key):
                    user_color_keys[user_color_key] = ''.join(
                        ['%x' % random.randint(0xc, 0xf) for x in range(3)])
                '<tr class="level-%s" style="background: #%s;">' % (
                        d['level'].lower(), user_color_keys[user_color_key])
                if (last_date != d['date']):
                    ' <td class="time">%s&nbsp;%s</td>' % (d['date'], d['hour'][:-4])
                    last_date = d['date']
                else:
                    ' <td class="time">%s</td>' % (d['hour'][:-4])
                if d['user_id'] ==  'anonymous':
                    userlabel = _('Anonymous')
                    ip = d['ip']
                    ' <td class="userlabel"><span title="%s">%s</span></td>' % (ip, userlabel)
                else:
                    try:
                        user = User.get(d['user_id'])
                    except KeyError:
                        userlabel = _('Unknown')
                    else:
                        if user.name is not None:
                            userlabel = htmltext(user.name.replace(str(' '), str('&nbsp;')))
                        else:
                            userlabel = _('Unknown')
                    ' <td class="userlabel">%s</td>' % userlabel
                ' <td class="message">%s</td>' % d['message']
                '</tr>\n'
            '</tbody>\n'
            '</table>\n'

        logfiles = [x for x in os.listdir(get_publisher().app_dir) if x.startswith(str('larpe.log'))]
        if len(logfiles) > 1:
            options = []
            for lfile in logfiles:
                firstline = open(os.path.join(get_publisher().app_dir, lfile)).readline()
                d = logger.readline(firstline)
                if not d:
                    continue
                if logfile == lfile:
                    selected = 'selected="selected" '
                else:
                    selected = ''
                options.append({'selected': selected, 'lfile': lfile,
                        'date': '%s %s' % (d['date'], d['hour'])})

            '<form id="other-log-select">'
            _('Select another logfile:')
            '<select name="logfile">'
            options.sort(lambda x,y: cmp(x['date'], y['date']))
            options.reverse()
            for option in options:
                option['since'] = str(_('Since: %s') % option['date'])[:-4]
                '<option value="%(lfile)s"%(selected)s>%(since)s</option>' % option
            '</select>'
            '<input type="submit" value="%s" />' % _('Submit')


    def download(self):
        request = get_request()
        logfile = request.get_field('logfile', 'larpe.log')
        if not logfile.startswith(str('larpe.log')) or str('/') in logfile:
            return template.error_page(_('Bad log file: %s') % logfile)
        logfilename = os.path.join(get_publisher().app_dir, logfile)
        response = get_response()
        response.set_content_type('text/x-log', 'iso-8859-1')
        response.set_header('content-disposition', 'attachment; filename=%s' % logfile)
        return open(logfilename).read()


class ByUserPages(Directory):
    _q_exports = ['']

    def __init__(self, component):
        try:
            self.user = User.get(component)
        except KeyError:
            raise TraversalError()

    def _q_index [html] (self):
        html_top('logger', title = _('Logs'))
        '<h2>%s - %s</h2>' % (_('User'), self.user.name)

        last_date = None
        '<table id="logs">'
        '<thead> <tr>'
        ' <th>%s</th>' % _('Time')
        ' <th>%s</th>' % _('Message')
        '<tr></thead>'
        '<tbody>'
        logfile = get_publisher().get_app_logger_filename()
        if os.path.exists(logfile):
            for line in open(logfile):
                d = logger.readline(line)
                if d['user_id'] != str(self.user.id):
                    continue
                '<tr>'
                if (last_date != d['date']):
                    ' <td class="time">%s&nbsp;%s</td>' % (d['date'], d['hour'][:-4])
                    last_date = d['date']
                else:
                    ' <td class="time">%s</td>' % (d['hour'][:-4])
                ' <td><a href="%s">%s</a></td>' % (d['url'], d['message'])
                '</tr>'
        '</tbody>'
        '</table>'

