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

from qommon.form import *

from field_prefill import FieldPrefill
from menu import html_top, command_icon

class FieldUI:
    def __init__(self, field_prefill):
        self.field_prefill = field_prefill

    def form_edit(self):
        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'name', title = _('Field name'), required = True,
            size = 50, value = self.field_prefill.name)
        form.add(StringWidget, 'xpath', title = _('Xpath of the attribute'), required = True,
            size = 50, value = self.field_prefill.xpath, hint=_('Example: /pp:PP/pp:InformalName'))
        form.add(IntWidget, 'number', title = _('Number of the field in the data'), required = True,
            size = 3, value = self.field_prefill.number,
            hint=_('Change it if there are multiple fields corresponding to the same Xpath and you want to get another than the first one'))
        form.add(CheckboxWidget, 'raw_xml', title=_('Get raw XML value'),
            value = self.field_prefill.raw_xml)
        form.add(StringWidget, 'regexp_match', title = _('Python regexp of a string to match'),
            size = 50, value = self.field_prefill.regexp_match)
        form.add(StringWidget, 'regexp_replacing', title = _('Python regexp of the replacing string'),
            size = 50, value = self.field_prefill.regexp_replacing)
        form.add(WidgetDict, 'select_options', title = _('Options mapping for a select field'),
                value = self.field_prefill.select_options, add_element_label = _('Add item'))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        return form

    def submit_edit(self, form):
        for f in ('name', 'xpath', 'number', 'raw_xml',  'regexp_match', 'regexp_replacing', 'select_options'):
            widget = form.get_widget(f)
            setattr(self.field_prefill, f, widget.parse())
        self.field_prefill.store()

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

    def __init__(self, field_id):
        self.field_prefill = FieldPrefill.get(field_id)
        self.field_ui = FieldUI(self.field_prefill)
        get_response().breadcrumb.append((field_id + '/', field_id))

    def _q_index [html] (self):
        form = self.field_ui.form_edit()
        redo = False

        if form.get_widget('cancel').parse():
            return redirect('..')

        if form.get_widget('select_options') and form.get_widget('select_options').get_widget('add_element').parse():
            form.clear_errors()
            redo = True

        if redo is False and form.is_submitted() and not form.has_errors():
            self.field_ui.submit_edit(form)
            return redirect('..')

        get_response().breadcrumb.append( ('edit', _('Edit')) )
        html_top('edit', title = _('Edit'))
        '<h2>%s</h2>' % _('Edit')

        form.render()

    def delete [html] (self):
        form = Form(enctype='multipart/form-data')
        form.widgets.append(HtmlWidget('<p>%s</p>' % _(
                        'You are about to irrevocably delete this field.')))
        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('delete_form', title = _('Delete Field'))
            '<h2>%s : %s</h2>' % (_('Delete Field'), self.field_prefill.id)
            form.render()
        else:
            self.field_prefill.remove_self()
            return redirect('..')


class FieldsDirectory(Directory):
    _q_exports = ['', 'new']

    def __init__(self, form_prefill):
        get_response().breadcrumb.append(('fields/', _('Fields')))
        self.form_prefill = form_prefill

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

    def _q_index [html] (self):
        html_top('fields', title = _('Fields'))
        """<ul id="nav-fields-admin">
          <li><a href="new">%s</a></li>
        </ul>""" % _('New Field')

        '<ul class="biglist">'

        for field_prefill in FieldPrefill.select(lambda x: x.form_id == self.form_prefill.id):
            if not field_prefill.name:
                continue

            # Split too long xpath
            xpath = field_prefill.xpath
            xpath_tokens = xpath.split(str('/'))
            if len(xpath_tokens) > 3:
                xpath = str('.../') + str('/').join(xpath_tokens[-3:])

            '<li>'
            '<strong class="label">%s</strong>' % field_prefill.name
            '<br />%s' % xpath
            '<p class="commands">'
            command_icon('%s/' % field_prefill.id, 'edit')
            command_icon('%s/delete' % field_prefill.id, 'remove')
            '</p></li>'
        '</ul>'

    def new [html] (self):
        get_response().breadcrumb.append(('new', _('New')) )
        field_prefill = FieldPrefill()
        field_prefill.form_id = self.form_prefill.id
        field_prefill.store()
        return redirect('%s/' % field_prefill.id)

