import re

from quixote import redirect

import site_authentication

class CirilSiteAuthentication(site_authentication.SiteAuthentication):
    plugin_name = 'ciril'

    def auto_detect_site(cls, html_doc):
        if re.search(
                """<form name="myForm" id="myForm" method="post" target="choixAppli" action="/cgi-bin/acces.exe" """,
                html_doc):
            return True
        return False
    auto_detect_site = classmethod(auto_detect_site)

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

        # If status is 500, fail without checking other criterias
        if status // 100 == 5:
            success = False
            return_content = redirect(self.host.get_return_url())

        regexp = re.compile(
            """javascript\:window\.open\('(/net_rh/accueil.php\?.*?)', '_blank'\)""",
            re.DOTALL | re.IGNORECASE)
        match = regexp.findall(data)
        if match:
            success = True
            return_content = redirect(match[0])

        return success, return_content

site_authentication.register_site_authentication_class(CirilSiteAuthentication)

