from django.utils.six.moves import urllib_parse
from django.utils.six.moves.urllib_request import urlopen, Request
from django_cas_ng.cas import CASClientV2
import logging


logger = logging.getLogger(__name__)


class CASClientRemie(CASClientV2):

    def verify_ticket(self, ticket):
        """Verifies CAS 2.0+ XML-based authentication ticket."""
        try:
            from xml.etree import ElementTree
        except ImportError:
            from elementtree import ElementTree

        user = None
        pgtiou = None

        params = [('ticket', ticket), ('service', self.service_url)]
        if self.proxy_callback:
            params.append(('pgtUrl', self.proxy_callback))

        url = (urllib_parse.urljoin(self.server_url, 'serviceValidate') + '?' +
               urllib_parse.urlencode(params))
        page = urlopen(url)
        try:
            response = page.read()
            logger.debug("Verify CAS response : ")
            logger.debug(response)
            tree = ElementTree.fromstring(response)
            if tree[0].tag.endswith('authenticationSuccess'):
                attributes = {}
                for element in tree[0]:
                    if element.tag.endswith('user'):
                        user = element.text
                    elif element.tag.endswith('prenom'):
                        attributes['first_name'] = element.text
                    elif element.tag.endswith('nom'):
                        attributes['last_name'] = element.text
                    elif element.tag.endswith('proxyGrantingTicket'):
                        pgtiou = element.text
                return user, attributes, pgtiou
            else:
                return None, None, None
        finally:
            page.close()
