import re
import urllib

from quixote import get_request, get_response, get_session

from qommon.misc import http_post_request
from qommon import get_logger

from larpe.qommon.misc import http_get_page
import site_authentication

class AgirheSiteAuthentication(site_authentication.SiteAuthentication):
    plugin_name = 'agirhe'

    def auto_detect_site(cls, html_doc):
        if re.search("""<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/""", 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)

        # Get the authentication page
        try:
            response, status, page, auth_header = http_get_page(self.host.auth_form_url, use_proxy=self.host.use_proxy)
        except Exception, err:
            print err
            return None, None

        # Get current hidden fields everytime
        self.parse_forms(page)
        if self.host.auth_form is not None:
            input_fields = self.parse_input_fields()
            self.parse_other_fields(input_fields)

        # Add hidden fields to the body
        for key, value in self.host.other_fields.iteritems():
            value = urllib.quote_plus(value)
            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)

        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

    # The 3 following functions have been copied from admin/hosts.ptl

    def parse_forms(self, page):
        '''Search for an authentication form'''
        # Get all forms
        regexp = re.compile("""<form.*?</form>""", re.DOTALL | re.IGNORECASE)
        found_forms = regexp.findall(page)
        if not found_forms:
            return
            #raise FormError, ('auth_check_url', '%s : %s' % (_('Failed to find any form'), self.host.auth_form_url))

        # Get the first form with a password field
        for found_form in found_forms:
            regexp = re.compile("""<input[^>]*?type=["']?password["']?[^>]*?>""", re.DOTALL | re.IGNORECASE)
            if regexp.search(found_form) is not None:
                self.host.auth_form = found_form
                break

    def parse_input_fields(self):
        '''Get all input fields'''
        regexp = re.compile("""<input[^>]*?>""", re.DOTALL | re.IGNORECASE)
        return regexp.findall(self.host.auth_form)

    def parse_other_fields(self, input_fields):
        '''Get the default value of all other fields'''
        self.host.other_fields = {}

        # Get hidden fields
        regexp = re.compile("""<input[^>]*?type=["']?hidden["']?[^>]*?>""", re.DOTALL | re.IGNORECASE)
        other_fields = regexp.findall(self.host.auth_form)

        # Only get first submit field
        regexp = re.compile("""<input[^>]*?type=["']?submit["']?[^>]*?>""", re.DOTALL | re.IGNORECASE)
        found = regexp.findall(self.host.auth_form)
        if found:
            if other_fields:
                other_fields.append(found[0])
            else:
                other_fields = found[0]

        for field in other_fields:
            try:
                regexp = re.compile("""name=["']?(.*?)["']?[\s/>]""", re.DOTALL | re.IGNORECASE)
                name = regexp.findall(field)[0]
                regexp = re.compile("""value=["'](.*?)["'][\s/>]""", re.DOTALL | re.IGNORECASE)
                value = regexp.findall(field)[0]
                self.host.other_fields[name] = value
                if not self.host.post_parameters.has_key(name):
                    self.host.post_parameters[name] = { 'enabled': True, 'value': value, 'immutable': False }
            except IndexError, e:
                continue

site_authentication.register_site_authentication_class(AgirheSiteAuthentication)

