import re

from quixote import get_request, get_response, get_session

from qommon.misc import http_post_request
from qommon import get_logger

import site_authentication

class ConcertoSiteAuthentication(site_authentication.SiteAuthentication):
    plugin_name = 'concerto'

    def auto_detect_site(cls, html_doc):
        if re.search("""<meta name="description" content="Page d'accueil du site Espace-Famille" />""", html_doc):
            return True
        return False
    auto_detect_site = classmethod(auto_detect_site)

    def local_auth_check_post(self, username, password, select={}, session_cookies=False):
        url = self.host.auth_check_url

        # Build request body
        body = '%s=%s&%s=%s' % (self.host.login_field_name, username, self.host.password_field_name, password)
        # Add select fields to the body
        for name, value in select.iteritems():
            body += '&%s=%s' % (name, value)
        # Add hidden fields to the body
        if self.host.send_hidden_fields:
            for key, value in self.host.other_fields.iteritems():
                body += '&%s=%s' % (key, value)

        # Build request HTTP headers
        headers = {'Content-Type': 'application/x-www-form-urlencoded',
                   'X-Forwarded-For': get_request().get_environ('REMOTE_ADDR', '-'),
                   'X-Forwarded-Host': self.host.reversed_hostname}
        
        # Add session id cookie
        if session_cookies is True:
            for key, value in self.host.other_fields.iteritems():
                headers['Cookie'] = 'JSESSIONID=' + value

        # Send request
        response, status, data, auth_headers = http_post_request(url, body, headers, self.host.use_proxy)

        cookies = response.getheader('Set-Cookie', None)
        self.host.cookies = []
        new_session_id = None
        if cookies is not None:
            cookies_list = []
            cookies_set_list = []
            for cookie in cookies.split(', '):
                # Drop the path and other attributes
                cookie_only = cookie.split('; ')[0]
                regexp = re.compile('=')
                if regexp.search(cookie_only) is None:
                    continue
                # Split name and value
                cookie_split = cookie_only.split('=')
                cookie_name = cookie_split[0]
                cookie_value = cookie_split[1]
                if cookie_name == 'JSESSIONID':
                    new_session_id = cookie_value
                cookies_list.append('%s=%s' % (cookie_name, cookie_value))
                set_cookie = '%s=%s; path=/demo' % (cookie_name, cookie_value)
                cookies_set_list.append(set_cookie)
                self.host.cookies.append(cookie_name)
            cookies_headers = '\r\nSet-Cookie: '.join(cookies_set_list)
            get_response().set_header('Set-Cookie', cookies_headers)
            self.host.store()
            get_session().cookies = '; '.join(cookies_list)
        else:
            get_logger().warn('No cookie from local authentication')

        if session_cookies is False:
            # Change idSession hidden field with new session id
            self.host.other_fields['idSession'] = new_session_id
            # Retry the request with the new session id
            return self.local_auth_check_post(username, password, select, session_cookies=True)
        else:
            return response.status, data

site_authentication.register_site_authentication_class(ConcertoSiteAuthentication)

