"""
    MoinMoin - Base class for Licensing actions

    @copyright: 2007 Nathan R. Yergler <nathan@yergler.net>
    @license: GNU GPL, see COPYING for details.
"""

import os
import sys
import urllib
import urllib2

from MoinMoin import wikiutil
from MoinMoin.Page import Page
from MoinMoin.PageEditor import PageEditor
from MoinMoin.action import ActionBase

REMOVE_LICENSE = "__remove"

def license_details(license_uri):
    """Retrieve the license details from the license URI; return a mapping
    containing at least the following keys:

    license_uri
    license_name
    license_img

    """

    if sys.version_info < (2, 5, 0):
        import elementtree.ElementTree as et
    else:
        import xml.etree.ElementTree as et

    license_xml = et.fromstring(
        urllib2.urlopen(
        "http://api.creativecommons.org/rest/dev/details?license-uri=%s"
        % license_uri).read())

    result = dict(
        license_uri = license_xml.find('license-uri').text,
        license_name = license_xml.find('license-name').text,
        license_img = license_xml.find('html/a/img').attrib.get('src', ''),
        )

    return result

class LicenseActionBase(ActionBase):
    """ Base class for license-related actions.
    """

    """LICENSE_PAGE_TEXT is a template for the license page text.
    It may contain Python string template expansion.  When expanding
    it will be supplied with the dictionary returned by license_details."""
    LICENSE_PAGE_TEXT=""
    
    def __init__(self, pagename, request):
        ActionBase.__init__(self, pagename, request)
        self.use_ticket = False
        _ = self._
        self.form_trigger = 'license'
        self.form_trigger_label = _('License')
        
    def check_condition(self):
        _ = self._

        # make sure the site licensing is turned on
        if not(self.request.cfg.page_license_enabled):
            return _("page_license_enabled is turned off in wikiconfig.py")

        # element tree is required; check for it's availability
        # if we're running Python 2.5, elementtree is include
        if sys.version_info < (2, 5, 0):
            try:
                import elementtree
            except ImportError, e:
                return _("This action requires the elementtree library, which does not seem to be available.")
        
        return None

    def get_license_pagename(self, pagename):
        """Return the page name where license information is stored.
        For single-page licensing, this is usually a sub-page of the
        page; for site-wide licensing, this is a page defined in the
        wikiconfig.py (page_license_page)."""

        raise NotImplementedError

    def get_license(self):
        """Load the license name and URL for the pagename.  Returns a
        mapping, including:

        license_uri
        license_name
        license_img

        """

        license_page = Page(self.request, self.get_license_pagename(self.pagename))
        license_info = {}

        if license_page.isStandardPage(False):
            # load the page
            for line in license_page.getlines():
                if line.split() and line.split()[0].lower() == "#pragma":
                    pragma, key, value = line.split(' ', 2)
                    license_info[key] = value

        return license_info

    def do_action(self):
        """ Add or remove the selected license. """
        _ = self._

        # get the selected license url
        license_url = self.form.get('license')[0]

        # check if the user is selecting or removing a license
        if license_url == REMOVE_LICENSE:

            # delete the license sub-page
            msg = "License removed."
            PageEditor(self.request,
                       self.get_license_pagename(self.pagename)).deletePage()

        else:
            # save the selected license

            # create or edit the license sub-page
            license_page = PageEditor(self.request,
                                      self.get_license_pagename(self.pagename))

            # get the license details from the web service
            details = license_details(license_url)

            # construct the page contents
            page_contents = ("""#pragma license_name %(license_name)s
#pragma license_uri %(license_uri)s
#pragma license_img %(license_img)s

""" + self.LICENSE_PAGE_TEXT) % details

            try:
                license_page.saveText(page_contents, license_page.current_rev())
                msg = _("License updated.")

            except PageEditor.Unchanged, e:
                msg = _("License not changed; nothing to save.")

        return (None, msg)

    def do_action_finish(self, success):
        if success:
            url = Page(self.request, self.pagename).url(self.request)
            self.request.http_redirect(url)
            self.request.finish()
        else:
            self.render_msg(self.make_form())

    def get_form_html(self, buttons_html):
        _ = self._

        # create our exit URL for when we return from the selector
        exit_url = "%s%s&license=1&license_url=[license_url]&license_name=[license_name]&license_img=[license_button]" % (
            self.request.getQualifiedURL(),
            self.request.makeURI(),
            )
        exit_url = urllib.quote(exit_url)

        # construct the URL to the CC partner interface
        logo_url = '%s%s/common/moinmoin.png' % (self.request.getQualifiedURL(),
                                                self.request.cfg.url_prefix)
        selector_url = 'http://creativecommons.org/license/' \
                       '?partner=moinlicense&partner_icon_url=%s' \
                       '&jurisdiction_choose=1&jurisdiction=-' \
                       '&exit_url=%s&lang=en' % (logo_url, exit_url)

        license_info = self.get_license()

        d = {
            'pagename': self.pagename,
            'license' : license_info.get('license_name', 'None'),
            'license_uri' : license_info.get('license_uri', ''),
            'license_label': _("Current License"),
            'new_license_label':_("New License"),
            'buttons_html': buttons_html,
            'selector_url':selector_url,
            'REMOVE_LICENSE':REMOVE_LICENSE
        }

        return '''
<table>
    <tr>
        <td class="label"><label><nobr>%(license_label)s</nobr></label></td>
        <td class="content"><nobr><a href="%(license_uri)s">%(license)s</a></nobr></td>
    </tr>
    <tr>
        <td class="label"><label>%(new_license_label)s</label></td>
        <td class="content">
            <select name="license">
                <script
                src="http://api.creativecommons.org/rest/dev/simple/chooser.js">
                <option value="----">----</option>
                <option value="%(REMOVE_LICENSE)s">Remove License</option>
            </select>
        </td>
    </tr>
    <tr>
        <td></td>
        <td class="buttons">
            %(buttons_html)s
        </td>
    </tr>
</table>
        
''' % d

