# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - CAS authentication

    Jasig CAS (see http://www.jasig.org/cas) authentication module.

    @copyright: 2012 MoinMoin:RichardLiao
    @license: GNU GPL, see COPYING for details.
"""

import sys
import os
import time, re
import urlparse
import urllib, urllib2
from netaddr import IPNetwork, IPAddress

from MoinMoin import log
logging = log.getLogger(__name__)

from MoinMoin.auth import BaseAuth
from MoinMoin import user, wikiutil
from MoinMoin.Page import Page
from anonymous_user import AnonymousAuth

class PublicCategories(AnonymousAuth):
    name = 'PublicCategories'

    def __init__(self, pub_cats=[], auth_username="Connexion"):
        AnonymousAuth.__init__(self, auth_username=auth_username)
        self.pub_cats=pub_cats

    def can_view(self, request):
        p = urlparse.urlparse(request.url)
        if p.path[1:] == "":
            return True
        if request.page is not None:
            sys.stderr.write("Getting page from cache")
            page = request.page
        else:
            pagename=unicode(urllib.unquote(p.path[1:]),'utf-8')
            if pagename.endswith(u'/'):
                pagename=pagename[:-1]
            page = Page(request, pagename)
        acl = page.getACL(request)
        if acl.acl and [a[0] for a in acl.acl if a[0] == 'All' and a[1].get('read',False)]:
            sys.stderr.write("acl +All:read\n")
            return False
        categories = page.getCategories(request)
        if categories:
            for cat in self.pub_cats:
                if cat in categories:
                    sys.stderr.write("%r dans la page %r\n" % (cat, p.path[1:]))
                    return True
        else:
            sys.stderr.write("categories is empty, searching in page body of %s\n" % p.path[1:])
            body = page.getPageText()
            for cat in self.pub_cats:
                if cat in body:
                    sys.stderr.write("%r dans la page %r\n" % (cat, p.path[1:]))
                    return True

        sys.stderr.write("%r n'est pas dans la page %r, %r\n" % (cat, p.path[1:], categories))
        return False


    def request(self, request, user_obj, **kw):
        user_obj, cont = AnonymousAuth.request(self, request, user_obj, **kw)
        if user_obj and not user_obj.valid and user_obj.auth_method == self.name:
            p = urlparse.urlparse(request.url)
            url = urlparse.urlunparse(('https', p.netloc, p.path, "", "", ""))
            action = request.args.get("action", "")
            # pas de redirection si action est déjà deny ou que l'utilisateur se connecte
           # if action not in [ "deny", "login"]:
            #    request.http_redirect(url + "?action=deny")
        return user_obj, cont

