import cPickle
import re
import os
import time

from quixote import get_publisher, get_request, get_response, redirect, get_session_manager
from quixote.directory import Directory
from quixote.html import htmltext
from quixote.util import dump_request

from qommon import errors

from menu import html_top

from authentic import misc
from authentic.form import *

class SessionsDir(Directory):
    _q_exports = ['', 'submit']

    def _q_traverse(self, path):
        get_response().breadcrumb.append(('sessions/', _('Sessions')))
        return Directory._q_traverse(self, path)

    def _q_index [html] (self):
        html_top('debug', title = _('Sessions'))
        '<form action="submit" enctype="multipart/form-data" method="post">'
        '<table>'
        '<thead><th></th><th>%s</th> <th>%s</th> <th>%s</th> <th>%s</th> <th></th></thead>' % (
                _('Remote IP'), _('User'), _('Creation Time'), _('Access Time'))
        '<tbody>'
        sessions = get_session_manager().values()
        sessions.sort(lambda x, y: cmp(x._access_time, y._access_time))
        identities_url = get_request().environ[str('SCRIPT_NAME')] + '/admin/identities/'
        for v in sessions:
            '<tr><td><a href="%s/">%s</a></td>' % (v.id, v.id)
            '<td>%s</td>' % v._remote_address
            if v.user:
                '<td><a href="%s%s/">%s</a></td>' % (identities_url, v.user, v.user)
            else:
                '<td></td>'
            '<td>%s</td>' % time.strftime(str('%m-%d %H:%M'), time.localtime(v._creation_time))
            '<td>%s</td>' % time.strftime(str('%m-%d %H:%M'), time.localtime(v._access_time))
            '<td><input type="checkbox" name="s" value="%s"/></td>' % v.id
            '</tr>'
        '</tbody></table>'
        '<input type="submit" name="delete" value="%s"/>' % _('Delete selected sessions')
        '</form>'

    def submit(self):
        request = get_request()
        session_manager = get_session_manager()
        if not 's' in request.form:
            return redirect('.')
        if type(request.form['s']) is not type([]):
            s = [request.form['s']]
        else:
            s = request.form['s']
        if request.form.has_key('delete'):
            for k in s:
                del session_manager[k]
            return redirect('.')

    def _q_lookup(self, component):
        return SessionUI(component)

class SessionUI(Directory):
    _q_exports = ['', 'delete']

    def __init__(self, component):
        try:
            self.session = get_session_manager()[component]
        except KeyError:
            raise errors.TraversalError()
        get_response().breadcrumb.append(('%s/' % component, _('Session')))

    def _q_index [html] (self):
        html_top('debug', _('Session'))
        attrs = [('user', _('User'), 's'),
                ('_remote_address', _('Remote Address'), 's'),
                ('_creation_time', _('Creation Time'), 't'),
                ('_access_time', _('Access Time'), 't'),
                ('lasso_session_dump', _('Lasso Session Dump'), 'p'),
                ('lasso_proxy_session_dump', _('Lasso Proxy Session Dump'), 'p'),
                ('lasso_login_dump', _('Lasso Login Dump'), 'p'),
                ('lasso_logout_dump', _('Lasso Logout Dump'), 'p'),
                ('name_identifiers', _('Name Identifiers'), 'l'),
                ]
        '<dl>'
        for attr, label, type in attrs:
            if not hasattr(self.session, str(attr)) or not getattr(self.session, str(attr)):
                continue
            '<dt>%s</dt>' % label
            if type == 's':
                '<dd>%s</dd>' % getattr(self.session, str(attr))
            if type == 'l':
                '<dd>%s</dd>' % repr(getattr(self.session, str(attr)))
            elif type == 't':
                '<dd>%s</dd>' % time.strftime(str('%Y-%m-%d %H:%M:%S'),
                        time.localtime(getattr(self.session, str(attr))))
            elif type == 'p':
                '<dd><pre>%s</pre></dd>' % getattr(self.session, str(attr))
        '</dl>'

class DebugDirectory(Directory):

    _q_exports = ['', 'sessions']

    def _q_traverse(self, path):
        get_response().breadcrumb.append(('debug/', _('Debug')))
        return Directory._q_traverse(self, path)

    def _q_index [html] (self):
        get_publisher().reload_cfg()
        html_top('debug', title = 'Debug')

        '<dl>'
        '<dt><a href="sessions/">%s</a><dt> <dd>%s</dd>' % (
                _('Sessions'), _('Manage user sessions'))
        '</dl>'

    sessions = SessionsDir()

