import os

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

from authentic.admin.menu import html_top, command_icon

import authentic.admin.root

from authentic.form import *

class IpCheckAdminDirectory(Directory):
    _q_exports = ['', 'email', 'message']

    def _q_index [html] (self):
        html_top('ipcheck', title = _('IP Check'))

        '<ul>'
        '<li><a href="message">%s</a></li>' % _('Edit Confirmation Message')
        '<li><a href="email">%s</a></li>' % _('Edit Confirmation Email')
        '</ul>'

    def message(self):
        return self.msg_edit('message', _('Confirmation Message'))

    def email(self):
        return self.msg_edit('email', _('Confirmation Email'),
                vars = ('name', 'url'))

    def msg_edit [html] (self, filename, title, vars = None):
        '<h2>%s</h2>' % title
        text = str(os.path.join(get_publisher().app_dir, 'ipcheck/%s' % filename))
        if os.path.exists(text):
            value = file(text).read()
        else:
            value = None
        form = Form(enctype='multipart/form-data')
        if vars:
            hint = _('Available variables: %s') % ', '.join(vars)
        else:
            hint = None
        form.add(TextWidget, 'text', cols = 80, rows = 25, value = value, hint = hint)
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_widget('cancel').parse():
            return redirect('.')

        if not form.is_submitted() or form.has_errors():
            html_top('ipcheck', title = _('Editing IP Check Message'))
            form.render()
        else:
            def submit():
                if not os.path.exists(os.path.join(get_publisher().app_dir, 'ipcheck')):
                    os.mkdir(os.path.join(get_publisher().app_dir, 'ipcheck'))
                value = form.get_widget('text').parse()
                file(text, 'w').write(value)
                return redirect('.')
            submit()

authentic.admin.root.register_page('ipcheck', IpCheckAdminDirectory(), N_('IP Check'))
