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.backoffice.menu import html_top
from wcs.qommon.admin.menu import command_icon
from wcs.qommon import get_cfg
from wcs.qommon import errors, misc
from wcs.qommon.form import *
from wcs.qommon.misc import strftime

from .events import Event, RemoteCalendar, get_default_event_tags



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

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

    def _q_index(self):
        form = Form(enctype='multipart/form-data')
        form.add_submit('edit', _('Edit'))
        form.add_submit('delete', _('Delete'))
        form.add_submit('update', _('Update'))
        form.add_submit('back', _('Back'))

        if form.get_submit() == 'edit':
            return redirect('edit')
        if form.get_submit() == 'update':
            return redirect('update')
        if form.get_submit() == 'delete':
            return redirect('delete')
        if form.get_submit() == 'back':
            return redirect('..')

        html_top('events', title = _('Remote Calendar: %s') % self.calendar.label)
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('Remote Calendar: %s') % self.calendar.label

        r += get_session().display_message()

        r += htmltext('<p>')
        self.calendar.url
        if self.calendar.error:
            r += htmltext(' - <span class="error-message">%s</span>') % self.calendar.get_error_message()
        r += htmltext('</p>')

        if not self.calendar.content:
            r += htmltext('<p>')
            r += _('No content has been retrieved yet.')
            r += htmltext('</p>')
        else:
            r += htmltext('<ul>')
            for ev in sorted(self.calendar.events, lambda x,y: cmp(x.date_start, y.date_start)):
                r += htmltext('<li>')
                if ev.date_start:
                    r += strftime(misc.date_format(), ev.date_start)
                if ev.date_end and ev.date_start[:3] != ev.date_end[:3]:
                    r += ' - '
                    r += strftime(misc.date_format(), ev.date_start)

                r += ' : '
                if ev.url:
                    r += htmltext('<a href="%s">%s</a>') % (ev.url, ev.title)
                else:
                    r += ev.title
                r += htmltext('</li>')
            r += htmltext('</ul>')

        r += form.render()
        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('events', title = _('Edit Remote Calendar: %s') % self.calendar.label)
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('Edit Remote Calendar: %s') % self.calendar.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.calendar.label)
        form.add(StringWidget, 'url', title = _('URL'), required = True,
                value = self.calendar.url, size = 40)
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        return form

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

    def delete(self):
        form = Form(enctype='multipart/form-data')
        form.widgets.append(HtmlWidget('<p>%s</p>' % _(
                        'You are about to irrevocably delete this remote calendar.')))
        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('events', title = _('Delete Remote Calendar'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Deleting Remote Calendar: %s') % self.calendar.label
            r += form.render()
            return r.getvalue()
        else:
            self.calendar.remove_self()
            return redirect('..')

    def update(self):
        get_session().message = ('info',
                _('Calendar update has been requested, reload in a few moments'))
        get_response().add_after_job('updating remote calendar',
                self.calendar.download_and_parse,
                fire_and_forget = True)
        return redirect('.')



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

    def _q_traverse(self, path):
        get_response().breadcrumb.append(('remote/', _('Remote Calendars')))
        return Directory._q_traverse(self, path)

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

    def new(self):
        calendar_ui = RemoteCalendarDirectory(RemoteCalendar())

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

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

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

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


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

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

    def _q_index(self):
        form = Form(enctype='multipart/form-data')
        form.add_submit('edit', _('Edit'))
        form.add_submit('delete', _('Delete'))
        form.add_submit('back', _('Back'))

        if form.get_submit() == 'edit':
            return redirect('edit')
        if form.get_submit() == 'delete':
            return redirect('delete')
        if form.get_submit() == 'back':
            return redirect('..')

        html_top('events', title = _('Event: %s') % self.event.title)
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('Event: %s') % self.event.title
        r += htmltext('<p>')
        r += self.event.description
        r += htmltext('</p>')
        r += htmltext('<ul>')
        if self.event.location:
            r += htmltext('<li>%s: %s</li>') % (_('Location'), self.event.location)
        if self.event.organizer:
            r += htmltext('<li>%s: %s</li>') % (_('Organizer'), self.event.organizer)
        if self.event.url:
            r += htmltext('<li>%s: <a href="%s">%s</a></li>') % (_('URL'), self.event.url, self.event.url)
        r += htmltext('</ul>')

        if self.event.more_infos:
            r += htmltext('<p>')
            r += self.event.more_infos
            r += htmltext('</p>')

        r += form.render()
        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('events', title = _('Edit Event: %s') % self.event.title)
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('Edit Event: %s') % self.event.title
        r += form.render()
        return r.getvalue()

    def form(self):
        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'title', title = _('Title'), required = True,
                value = self.event.title)
        form.add(TextWidget, 'description', title = _('Description'),
                cols = 70, rows = 10,
                required = True, value = self.event.description)
        form.add(StringWidget, 'url', title = _('URL'), required = False,
                value = self.event.url, size = 40)
        form.add(DateWidget, 'date_start', title = _('Start Date'), required = True,
                value = strftime(misc.date_format(), self.event.date_start))
        form.add(DateWidget, 'date_end', title = _('End Date'), required = False,
                value = strftime(misc.date_format(), self.event.date_end))
        form.add(TextWidget, 'location', title = _('Location'),
                cols = 70, rows = 4,
                required = False, value = self.event.location)
        form.add(StringWidget, 'organizer', title = _('Organizer'), required = False,
                value = self.event.organizer, size = 40)
        form.add(TextWidget, 'more_infos', title = _('More informations'),
                cols = 70, rows = 10,
                required = False, value = self.event.more_infos)
        form.add(TagsWidget, 'keywords', title = _('Keywords'),
                value = self.event.keywords, size = 50,
                known_tags = get_cfg('misc', {}).get('event_tags', get_default_event_tags()))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        return form

    def submit(self, form):
        for k in ('title', 'description', 'url', 'date_start', 'date_end',
                    'organizer', 'location', 'more_infos', 'keywords'):
            widget = form.get_widget(k)
            if widget:
                if k in ('date_start', 'date_end'):
                    # convert dates to 9-item tuples
                    v = widget.parse()
                    if v:
                        setattr(self.event, k, time.strptime(v, misc.date_format()))
                    else:
                        setattr(self.event, k, None)
                else:
                    setattr(self.event, k, widget.parse())
        self.event.store()

    def delete(self):
        form = Form(enctype='multipart/form-data')
        form.widgets.append(HtmlWidget('<p>%s</p>' % _(
                        'You are about to irrevocably delete this event.')))
        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('events', title = _('Delete Event'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Deleting Event: %s') % self.event.title
            r += form.render()
            return r.getvalue()
        else:
            self.event.remove_self()
            return redirect('..')




class EventsDirectory(AccessControlled, Directory):
    _q_exports = ['', 'new', 'listing', 'remote']
    label = N_('Events')

    remote = RemoteCalendarsDirectory()

    def is_accessible(self, user):
        from .backoffice import check_visibility
        return check_visibility('events', 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 Events Management'),
                    location_hint = 'backoffice')

        get_response().breadcrumb.append(('events/', _('Events')))


    def _q_index(self):
        html_top('events', _('Events'))
        r = TemplateIO(html=True)

        get_response().filter['sidebar'] = self.get_sidebar()

        r += htmltext('<div class="splitcontent-left">')

        r += htmltext('<div class="bo-block">')
        events = Event.select()
        r += htmltext('<h2>%s</h2>') % _('Events')
        if not events:
            r += htmltext('<p>')
            r += _('There is no event defined at the moment.')
            r += htmltext('</p>')
        r += htmltext('<ul class="biglist" id="events-list">')
        for l in events:
            event_id = l.id
            r += htmltext('<li class="biglistitem" id="itemId_%s">') % event_id
            r += htmltext('<strong class="label"><a href="%s/">%s</a></strong>') % (event_id, l.title)
            r += ' - '
            r += l.format_date()
            r += htmltext('<p class="commands">')
            r += command_icon('%s/edit' % event_id, 'edit')
            r += command_icon('%s/delete' % event_id, 'remove')
            r += htmltext('</p></li>')
        r += htmltext('</ul>')
        r += htmltext('</div>')
        r += htmltext('</div>')

        r += htmltext('<div class="splitcontent-right">')
        r += htmltext('<div class="bo-block">')
        rcalendars = RemoteCalendar.select()
        r += htmltext('<h2>%s</h2>') % _('Remote Calendars')
        if not rcalendars:
            r += htmltext('<p>')
            r += _('There is no remote calendars defined at the moment.')
            r += htmltext('</p>')

        r += htmltext('<ul class="biglist" id="events-list">')
        for l in rcalendars:
            rcal_id = l.id
            r += htmltext('<li class="biglistitem" id="itemId_%s">') % rcal_id
            r += htmltext('<strong class="label"><a href="remote/%s/">%s</a></strong>') % (rcal_id, l.label)
            r += htmltext('<p class="details">')
            r += l.url
            if l.error:
                r += htmltext('<br /><span class="error-message">%s</span>') % l.get_error_message()
            r += htmltext('</p>')
            r += htmltext('<p class="commands">')
            r += command_icon('remote/%s/edit' % rcal_id, 'edit')
            r += command_icon('remote/%s/delete' % rcal_id, 'remove')
            r += htmltext('</p></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="new">%s</a></li>') % _('New Event')
        r += htmltext('  <li><a class="new-item" href="remote/new">%s</a></li>') % _('New Remote Calendar')
        r += htmltext('</ul>')
        return r.getvalue()

    def new(self):
        event_ui = EventDirectory(Event())

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

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

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

    def _q_lookup(self, component):
        try:
            event = Event.get(component)
        except KeyError:
            raise errors.TraversalError()
        get_response().breadcrumb.append((str(event.id), event.title))
        return EventDirectory(event)

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