import time

from quixote import get_request, get_response, get_session, redirect
from quixote.directory import Directory, AccessControlled
from quixote.html import TemplateIO, htmltext

import wcs
import wcs.admin.root

from wcs.qommon import _
from wcs.qommon import errors, misc
from wcs.qommon.form import *
from wcs.qommon.backoffice.menu import html_top
from wcs.qommon import get_cfg

from .strongbox import StrongboxType, StrongboxItem



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

    def __init__(self, strongboxtype):
        self.strongboxtype = strongboxtype

    def _q_index(self):
        html_top('strongbox', title = _('Item Type: %s') % self.strongboxtype.label)
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('Item Type: %s') % self.strongboxtype.label
        get_response().filter['sidebar'] = self.get_sidebar()
        r += get_session().display_message()

        if self.strongboxtype.validation_months:
            r += htmltext('<div class="bo-block">')
            r += htmltext('<ul>')
            r += htmltext('<li>')
            r += _('Number of months of validity:')
            r += ' '
            r += self.strongboxtype.validation_months
            r += htmltext('</li>')
            r += htmltext('</ul>')
            r += htmltext('</div>')

        return r.getvalue()

    def get_sidebar(self):
        r = TemplateIO(html=True)
        r += htmltext('<ul>')
        r += htmltext('<li><a href="edit">%s</a></li>') % _('Edit')
        r += htmltext('<li><a href="delete">%s</a></li>') % _('Delete')
        r += htmltext('</ul>')
        return r.getvalue()

    def edit(self):
        form = self.form()
        if form.get_submit() == 'cancel':
            return redirect('.')

        if form.is_submitted() and not form.has_errors():
            self.submit(form)
            return redirect('..')

        html_top('strongbox', title = _('Edit Item Type: %s') % self.strongboxtype.label)
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('Edit Item Type: %s') % self.strongboxtype.label
        r += form.render()
        return r.getvalue()

    def form(self):
        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'label', title = _('Label'), required = True,
                value = self.strongboxtype.label)
        form.add(IntWidget, 'validation_months', title=_('Number of months of validity'),
                value=self.strongboxtype.validation_months,
                hint=_('Use 0 if there is no expiration'))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        return form

    def submit(self, form):
        for k in ('label', 'validation_months'):
            widget = form.get_widget(k)
            if widget:
                setattr(self.strongboxtype, k, widget.parse())
        self.strongboxtype.store()

    def delete(self):
        form = Form(enctype='multipart/form-data')
        form.widgets.append(HtmlWidget('<p>%s</p>' % _(
                        'You are about to irrevocably delete this item type.')))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_submit() == 'cancel':
            return redirect('..')
        if not form.is_submitted() or form.has_errors():
            get_response().breadcrumb.append(('delete', _('Delete')))
            html_top('strongbox', title = _('Delete Item Type'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Deleting Item Type: %s') % self.strongboxtype.label
            r += form.render()
            return r.getvalue()
        else:
            self.strongboxtype.remove_self()
            return redirect('..')


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

    def _q_traverse(self, path):
        get_response().breadcrumb.append(('types/', _('Item Types')))
        return Directory._q_traverse(self, path)

    def _q_index(self):
        return redirect('..')

    def new(self):
        type_ui = StrongboxTypeDirectory(StrongboxType())

        form = type_ui.form()
        if form.get_submit() == 'cancel':
            return redirect('.')

        if form.is_submitted() and not form.has_errors():
            type_ui.submit(form)
            return redirect('%s/' % type_ui.strongboxtype.id)

        get_response().breadcrumb.append(('new', _('New Item Type')))
        html_top('strongbox', title = _('New Item Type'))
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('New Item Type')
        r += form.render()
        return r.getvalue()

    def _q_lookup(self, component):
        try:
            strongboxtype = StrongboxType.get(component)
        except KeyError:
            raise errors.TraversalError()
        get_response().breadcrumb.append((str(strongboxtype.id), strongboxtype.label))
        return StrongboxTypeDirectory(strongboxtype)


class StrongboxDirectory(AccessControlled, Directory):
    _q_exports = ['', 'types', 'add', 'add_to']
    label = N_('Strongbox')

    types = StrongboxTypesDirectory()

    def is_accessible(self, user):
        from .backoffice import check_visibility
        return check_visibility('strongbox', user)

    def _q_access(self):
        user = get_request().user
        if not user:
            raise errors.AccessUnauthorizedError()

        if not self.is_accessible(user):
            raise errors.AccessForbiddenError(
                    public_msg = _('You are not allowed to access Strongbox Management'),
                    location_hint = 'backoffice')

        get_response().breadcrumb.append(('strongbox/', _('Strongbox')))


    def _q_index(self):
        html_top('strongbox', _('Strongbox'))
        r = TemplateIO(html=True)
        get_response().filter['sidebar'] = self.get_sidebar()

        r += get_session().display_message()

        r += htmltext('<div class="splitcontent-left">')
        r += htmltext('<div class="bo-block">')
        r += htmltext('<h2>%s</h2>') % _('Propose a file to a user')
        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'q', title = _('User'), required=True)
        form.add_submit('search', _('Search'))
        r += form.render()
        if form.is_submitted() and not form.has_errors():
            q = form.get_widget('q').parse()
            users = self.search_for_users(q)
            if users:
                if len(users) == 1:
                    return redirect('add_to?user_id=%s' % users[0].id)
                if len(users) < 50:
                    r += _('(first 50 users only)')
                r += htmltext('<ul>')
                for u in users:
                    r += htmltext('<li><a href="add_to?user_id=%s">%s</a></li>') % (u.id, u.display_name)
                r += htmltext('</ul>')
            else:
                r += _('No user found.')
        r += htmltext('</div>')
        r += htmltext('</div>')

        r += htmltext('<div class="splitcontent-right">')
        r += htmltext('<div class="bo-block">')
        types = StrongboxType.select()
        r += htmltext('<h2>%s</h2>') % _('Item Types')
        if not types:
            r += htmltext('<p>')
            r += _('There is no item types defined at the moment.')
            r += htmltext('</p>')

        r += htmltext('<ul class="biglist" id="strongbox-list">')
        for l in types:
            type_id = l.id
            r += htmltext('<li class="biglistitem" id="itemId_%s">') % type_id
            r += htmltext('<strong class="label"><a href="types/%s/">%s</a></strong>') % (type_id, l.label)
            r += htmltext('</li>')
        r += htmltext('</ul>')
        r += htmltext('</div>')
        r += htmltext('</div>')
        return r.getvalue()

    def get_sidebar(self):
        r = TemplateIO(html=True)
        r += htmltext('<ul id="sidebar-actions">')
        r += htmltext('  <li><a class="new-item" href="types/new">%s</a></li>') % _('New Item Type')
        r += htmltext('</ul>')
        return r.getvalue()

    def search_for_users(self, q):
        if hasattr(get_publisher().user_class, 'search'):
            return get_publisher().user_class.search(q)
        if q:
            users = [x for x in get_publisher().user_class.select()
                     if q in (x.name or '') or q in (x.email or '')]
            return users
        else:
            return []

    def get_form(self):
        types = [(x.id, x.label) for x in StrongboxType.select()]
        form = Form(action='add', enctype='multipart/form-data')
        form.add(StringWidget, 'description', title=_('Description'), size=60)
        form.add(FileWidget, 'file', title=_('File'), required=True)
        form.add(SingleSelectWidget, 'type_id', title=_('Document Type'),
                 options = [(None, _('Not specified'))] + types)
        form.add(DateWidget, 'date_time', title = _('Document Date'))
        form.add_submit('submit', _('Upload'))
        return form

    def add(self):
        form = self.get_form()
        form.add(StringWidget, 'user_id', title=_('User'))
        if not form.is_submitted():
           return redirect('.')

        sffile = StrongboxItem()
        sffile.user_id = form.get_widget('user_id').parse()
        sffile.description = form.get_widget('description').parse()
        sffile.proposed_time = time.localtime()
        sffile.proposed_id = get_request().user.id
        sffile.type_id = form.get_widget('type_id').parse()
        v = form.get_widget('date_time').parse()
        sffile.set_expiration_time_from_date(v)
        sffile.store()
        sffile.set_file(form.get_widget('file').parse())
        sffile.store()
        return redirect('.')

    def add_to(self):
        form = Form(enctype='multipart/form-data', action='add_to')
        form.add(StringWidget, 'user_id', title = _('User'), required=True)
        try:
            user_id = form.get_widget('user_id').parse()
            user = get_publisher().user_class.get(user_id)
        except:
            return redirect('.')
        if not user:
            return redirect('.')
        get_request().form = {}
        get_request().environ['REQUEST_METHOD'] = 'GET'

        html_top('strongbox', _('Strongbox'))
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s %s</h2>') % (_('Propose a file to:'), user.display_name)
        form = self.get_form()
        form.add(HiddenWidget, 'user_id', title=_('User'), value=user.id)
        r += form.render()
        return r.getvalue()
