import re
import urlparse

from quixote import get_request, get_response, get_session

from qommon.misc import http_post_request, http_get_page
from qommon import get_logger

import site_authentication

class EgroupwareSiteAuthentication(site_authentication.SiteAuthentication):
    plugin_name = 'egroupware'

    def auto_detect_site(cls, html_doc):
        if re.search("""<meta name="description" content="eGroupWare" />""", html_doc):
            return True
        return False
    auto_detect_site = classmethod(auto_detect_site)

    def local_auth_check_post(self, username, password, select=None):
        select = select or {}
        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}

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

        # The specific code is these 2 lines and the called function
        if self.host.name.startswith('egroupware'):
            data = self.get_data_after_redirects(response, data)

        cookies = response.getheader('Set-Cookie', None)
        self.host.cookies = []
        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]
                cookies_list.append('%s=%s' % (cookie_name, cookie_value))
                set_cookie = '%s=%s; path=/' % (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')

        return response.status, data

    def get_data_after_redirects(self, response, data):
        status = response.status
        headers = {'X-Forwarded-For': get_request().get_environ('REMOTE_ADDR', '-'),
                   'X-Forwarded-Host': self.host.reversed_hostname}
        while status == 302:
            location = response.getheader('Location', None)
            if location is not None:
                url_tokens = urlparse.urlparse(self.host.auth_check_url)
                url = '%s://%s%s'% (url_tokens[0], url_tokens[1], location)
                response, status, data, auth_headers = http_get_page(
                    url, headers, self.host.use_proxy)
        return data

site_authentication.register_site_authentication_class(EgroupwareSiteAuthentication)

