# Copyright (c) 2002-2007 Infrae. All rights reserved.
# See also LICENSE.txt
# Zope 3
from zope.component import getView
from zope.pagetemplate.interfaces import IPageTemplate
# Five
from silvaview import SilvaView
# SilvaLayout

# misc
from DateTime import DateTime

class Buttons(SilvaView):
    def getBackUrl(self):
        # to make sure we don't get cached back pages, we need to set the
        # right headers here (XXX perhaps this is more suitable somewhere
        # else?)
        self._setHeaders()

        request = self.context.REQUEST
        # make sure the back button points to the last edit screen visited
        back_url = request.SESSION.get('public_preview_back_url', None)
        # [sic]
        referer = request.get('HTTP_REFERER', None)
        if (referer and 'edit' in referer.split('/') and
                not referer.endswith('/preview_html')):
            # set the referer as the target for the back button...
            request.SESSION['public_preview_back_url'] = referer
            back_url = referer
        return back_url

    def getMessage(self):
        return self.request.get('message', '')

    def getMessageType(self):
        return self.request.get('message_type', '')

    def isUnapproved(self):
        obj = self.context.aq_inner
        if not hasattr(obj, 'get_unapproved_version'):
            return False

        return obj.get_unapproved_version() is not None
    def _setHeaders(self):
        request = self.context.REQUEST
        response = request.RESPONSE
        headers = [('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT'),
                    ('Last-Modified',
                        DateTime("GMT").strftime("%a, %d %b %Y %H:%M:%S GMT")),
                    ('Cache-Control', 'no-cache, must-revalidate'),
                    ('Cache-Control', 'post-check=0, pre-check=0'),
                    ('Pragma', 'no-cache'),
                    ]

        placed = []
        for key, value in headers:
            if key not in placed:
                response.setHeader(key, value)
                placed.append(key)
            else:
                response.addHeader(key, value)

class PublishAction(SilvaView):
    def __call__(self):
        """
        """
        from DateTime import DateTime
        now = DateTime()

        request = self.request
        session = request.SESSION
        obj = self.context.aq_inner
        message = 'Content is published'
        message_type = 'feedback'
        publish = True
        if not obj.implements_versioning():
            message = 'not applicable'
            message_type = 'error'
            publish = False
        elif obj.is_version_approved():
            message = 'version already approved'
            message_type = 'error'
            publish = False
        if not obj.get_unapproved_version():
            if obj.is_version_published():
                message = 'version already public'
                message_type = 'error'
                publish = False
            obj.create_copy()

        if publish:
            # publish
            obj.set_unapproved_version_publication_datetime(now)
            obj.approve_version()
            request.RESPONSE.redirect(self.context.aq_inner.absolute_url() + '/edit/tab_status')
            return ''

        request.form['message_type'] = message_type
        request.form['message'] = unicode(message)
        view = getView(self.context, 'preview_html', request)
        view =  view.__of__(self.context)
        return view()
