from quixote import redirect
from quixote.directory import Directory

from menu import *

from larpe import errors
from larpe import misc
from larpe.roles import Role
from larpe.form import *

class RoleUI:
    def __init__(self, role):
        self.role = role

    def form_new(self):
        form = Form(enctype="multipart/form-data")
        form.add(StringWidget, "name", title = _('Role Name'), required = True, size=30)
        form.add(TextWidget, "details", title = _('Role Details'), required = False,
                cols = 40, rows = 5)
        form.add(WidgetList, 'emails', title = _('Role Emails'), element_type = StringWidget,
                add_element_label = _('Add Email'),
                element_kwargs = {'render_br': False, 'size': 30})
        form.add_submit("submit", _("Submit"))
        form.add_submit("cancel", _("Cancel"))
        return form

    def form_edit(self):
        form = Form(enctype="multipart/form-data")
        form.add_hidden('id', value = self.role.id)
        form.add(StringWidget, "name", title = _('Role Name'), required = True, size=30,
                value = self.role.name)
        form.add(TextWidget, "details", title = _('Role Details'), required = False,
                cols = 40, rows = 5, value = self.role.details)
        form.add(WidgetList, 'emails', title = _('Role Emails'), element_type = StringWidget,
                value = self.role.emails,
                add_element_label = _('Add Email'),
                element_kwargs = {'render_br': False, 'size': 30})
        form.add_submit("submit", _("Submit"))
        form.add_submit("cancel", _("Cancel"))
        return form

    def submit_form(self, form):
        if self.role:
            role = self.role
        else:
            role = Role(name = form.get_widget('name').parse())
        for f in ('name', 'details'):
            setattr(role, f, form.get_widget(f).parse())
        role.emails = [x for x in form.get_widget('emails').parse() or [] if x]
        role.store()


class RolePage(Directory):
    _q_exports = ["edit", "delete"]

    def __init__(self, component):
        self.role = Role.get(component)
        self.role_ui = RoleUI(self.role)
        get_response().breadcrumb.append((component + '/', self.role.name))

    def edit [html] (self):
        form = self.role_ui.form_edit()
        if form.get_widget('cancel').parse():
            return redirect('..')

        if not form.is_submitted() or form.has_errors():
            get_response().breadcrumb.append( ('edit', _('Edit')) )
            html_top('roles', title = _('Edit Role'))
            '<h2>%s</h2>' % _('Edit Role')
            form.render()
        else:
            self.role_ui.submit_form(form)
            return redirect('..')

    def delete [html] (self):
        form = Form(enctype="multipart/form-data")
        form.widgets.append(HtmlWidget('<p>%s</p>' % _(
                        "You are about to irrevocably delete this role.")))
        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():
            get_response().breadcrumb.append(('delete', _('Delete')))
            html_top('roles', title = _('Delete Role'))
            '<h2>%s %s</h2>' % (_('Deleting Role:'), self.role.name)
            form.render()
        else:
            self.role.remove_self()
            return redirect('..')


class RolesDirectory(Directory):

    _q_exports = ["", "new"]

    def _q_index [html] (self):
        get_response().breadcrumb.append(('roles/', _('Roles')))
        html_top('roles', title = _('Roles'))
        '<div class="explanation">'
        '<p>%s</p>' % _('Roles are useful for two different things:')
        '<ol>'
        ' <li>%s</li>' % _('To know who will receive and manage a given type of form.')
        ' <li>%s</li>' % _('To know who can fill a given type of form.')
        '</ol>'
        '</div>'

        """<ul id="nav-roles-admin">
          <li><a href="new">%s</a></li>
        </ul>""" % _('New Role')

        '<ul class="biglist">'
        for role in Role.select(order_by = 'name'):
            '<li>'
            '<strong class="label">%s</strong>' % role.name
            '<p class="commands">'
            command_icon('%s/edit' % role.id, 'edit')
            command_icon('%s/delete' % role.id, 'remove')
            '</p></li>'
        '</ul>'

    def new [html] (self):
        get_response().breadcrumb.append(('roles/', _('Roles')))
        get_response().breadcrumb.append(('new', _('New')) )
        role_ui = RoleUI(None)
        form = role_ui.form_new()
        if form.get_widget('cancel').parse():
            return redirect('.')

        if not form.is_submitted() or form.has_errors() or form.get_submit() is True:
            html_top('roles', title = _('New Role'))
            '<h2>%s</h2>' % _('New Role')
            form.render()
        else:
            role_ui.submit_form(form)
            return redirect('.')
    
    def _q_lookup(self, component):
        get_response().breadcrumb.append(('roles/', _('Roles')))
        return RolePage(component)
