# w.c.s. - web application for online forms
# Copyright (C) 2005-2016  Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

from quixote import redirect
from quixote.directory import Directory
from quixote.html import TemplateIO, htmltext

from wcs.qommon import _
from wcs.qommon import errors
from wcs.qommon.form import *
from wcs.qommon.backoffice.menu import html_top
from wcs.wscalls import NamedWsCall, WsCallRequestWidget

class NamedWsCallUI(object):
    def __init__(self, wscall):
        self.wscall = wscall
        if self.wscall is None:
            self.wscall = NamedWsCall()

    def get_form(self):
        form = Form(enctype='multipart/form-data',
                advanced_label=_('Additional options'))
        form.add(StringWidget, 'name', title=_('Name'), required=True, size=30,
                value=self.wscall.name)
        form.add(TextWidget, 'description', title=_('Description'),
                cols=40, rows=5,
                value=self.wscall.description)
        if self.wscall.slug:
            form.add(StringWidget, 'slug',
                    value=self.wscall.slug,
                    title=_('Identifier'),
                    hint=_('Beware it is risky to change it'),
                    required=True, advanced=True,
                    )
        form.add(WsCallRequestWidget, 'request',
                value=self.wscall.request,
                title=_('Request'), required=True)

        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        return form

    def submit_form(self, form):
        name = form.get_widget('name').parse()
        if self.wscall.slug:
            slug = form.get_widget('slug').parse()
        else:
            slug = None

        for wscall in NamedWsCall.select():
            if wscall.id == self.wscall.id:
                continue
            if name == wscall.name:
                form.get_widget('name').set_error(_('This name is already used.'))
            if slug == wscall.slug:
                form.get_widget('slug').set_error(_('This value is already used.'))
        if form.has_errors():
            raise ValueError()

        self.wscall.name = name
        self.wscall.description = form.get_widget('description').parse()
        self.wscall.request = form.get_widget('request').parse()
        if self.wscall.slug:
            self.wscall.slug = slug
        self.wscall.store()


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

    def __init__(self, component):
        try:
            self.wscall = NamedWsCall.get(component)
        except KeyError:
            raise errors.TraversalError()
        self.wscall_ui = NamedWsCallUI(self.wscall)
        get_response().breadcrumb.append((component + '/', self.wscall.name))

    def _q_index(self):
        html_top('wscalls', title=self.wscall.name)
        r = TemplateIO(html=True)

        r += htmltext('<div id="appbar">')
        r += htmltext('<h2>%s - ') % _('Webservice Call')
        r += self.wscall.name
        r += htmltext('</h2>')
        r += htmltext('<span class="actions">')
        r += htmltext('<a href="delete" rel="popup">%s</a>') % _('Delete')
        r += htmltext('<a href="edit">%s</a>') % _('Edit')
        r += htmltext('</span>')
        r += htmltext('</div>')

        if self.wscall.description:
            r += htmltext('<div class="bo-block">')
            r += self.wscall.description
            r += htmltext('</div>')

        if self.wscall.request:
            r += htmltext('<div class="bo-block">')
            r += htmltext('<h3>%s</h3>') % _('Parameters')
            r += htmltext('<ul>')
            if self.wscall.request.get('url'):
                r += htmltext('<li>%s %s</li>') % (
                        _('URL:'),
                        self.wscall.request.get('url'))
            if self.wscall.request.get('request_signature_key'):
                r += htmltext('<li>%s %s</li>') % (
                        _('Request Signature Key:'),
                        self.wscall.request.get('request_signature_key'))
            if self.wscall.request.get('qs_data'):
                r += htmltext('<li>%s<ul>') % _('Query string data:')
                for k, v in self.wscall.request.get('qs_data').items():
                    r += htmltext('<li>%s %s</li>') % (_('%s:') % k, v)
                r += htmltext('</ul></li>')
            r += htmltext('<li>%s %s</li>') % (
                    _('Method:'),
                    'POST' if self.wscall.request.get('method') == 'POST' else 'GET')
            if self.wscall.request.get('post_data'):
                r += htmltext('<li>%s<ul>') % _('POST data:')
                for k, v in self.wscall.request.get('post_data').items():
                    r += htmltext('<li>%s %s</li>') % (_('%s:') % k, v)
                r += htmltext('</ul></li>')
            r += htmltext('</ul>')
            r += htmltext('</div>')

        return r.getvalue()

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

        if form.get_submit() == 'submit' and not form.has_errors():
            try:
                self.wscall_ui.submit_form(form)
            except ValueError:
                pass
            else:
                return redirect('../%s/' % self.wscall.id)

        get_response().breadcrumb.append( ('edit', _('Edit')) )
        html_top('wscalls', title = _('Edit webservice call'))
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('Edit webservice call')
        r += form.render()
        return r.getvalue()

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


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

    def _q_traverse(self, path):
        get_response().breadcrumb.append( ('wscalls/', _('Webservice Calls')) )
        return super(NamedWsCallsDirectory, self)._q_traverse(path)

    def _q_index(self):
        get_response().add_javascript(['jquery.js', 'jquery-ui.js', 'biglist.js',
            'qommon.wysiwyg.js'])

        html_top('wscalls', title=_('Webservice Calls'))
        r = TemplateIO(html=True)

        r += htmltext('<div id="appbar">')
        r += htmltext('<h2>%s</h2>') % _('Webservice Calls')
        r += htmltext('<span class="actions">')
        r += htmltext('<a class="new-item" href="new">%s</a>') % _('New webservice call')
        r += htmltext('</span>')
        r += htmltext('</div>')
        r += htmltext('<ul class="biglist" id="wscall-list">')
        wscalls = NamedWsCall.select(order_by='name')
        for wscall in wscalls:
            r += htmltext('<li class="biglistitem" id="itemId_%s">') % wscall.id
            r += htmltext('<strong class="label"><a href="%s/">%s (%s)</a></strong>') % (
                            wscall.id, wscall.name, wscall.slug)
            r += htmltext('</li>')
        r += htmltext('</ul>')
        r += htmltext('</div>')
        return r.getvalue()

    def new(self):
        get_response().breadcrumb.append( ('new', _('New')) )
        wscall_ui = NamedWsCallUI(None)
        form = wscall_ui.get_form()
        if form.get_widget('cancel').parse():
            return redirect('.')

        if form.get_submit() == 'submit' and not form.has_errors():
            try:
                wscall_ui.submit_form(form)
            except ValueError:
                pass
            else:
                return redirect('.')

        html_top('wscalls', title = _('New webservice call'))
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % _('New webservice call')
        r += form.render()
        return r.getvalue()

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