import re

from quixote import get_response, redirect
from quixote.html import htmltext

import site_authentication

class SympaSiteAuthentication(site_authentication.SiteAuthentication):
    plugin_name = 'sympa'

    def auto_detect_site(cls, html_doc):
        if re.search("""<FORM ACTION="/wwsympa.fcgi" METHOD=POST>""", html_doc):
            return True
        return False
    auto_detect_site = classmethod(auto_detect_site)

    def check_auth(self, status, data):
        success = False
        return_content = ''

        if self.host.auth_system == 'password':
            # If there is a password field, authentication probably failed
            regexp = re.compile(
                """<input[^>]*?type=["']?password["']?[^>]*?>""", re.DOTALL | re.IGNORECASE)
            if not regexp.findall(data):
                success = True
                # The specific part is only these 2 lines
                get_response().filter.update({'no_template': True})
                return_content = htmltext(data)
        elif self.host.auth_system == 'status':
            match_status = int(self.host.auth_match_status)
            if match_status == status:
                success = True
                return_content = redirect(self.host.return_url)
        elif self.host.auth_system == 'match_text':
            # If the auth_match_text is not matched, it means the authentication is successful
            regexp = re.compile(self.host.auth_match_text, re.DOTALL)
            if not regexp.findall(data):
                success = True
                return_content = redirect(self.host.get_return_url())

        return success, return_content

site_authentication.register_site_authentication_class(SympaSiteAuthentication)
