import re
import BeautifulSoup
from net.grinder.script.Grinder import grinder
from net.grinder.plugin.http import HTTPPluginControl
from utils import write_to_file 

def find_text(source, patternBefore, patternAfter, pattern = '.*', group = 1):
    '''Find the text between the given batterns'''
    p = re.compile(patternBefore + '(' + pattern + ')' + patternAfter, re.IGNORECASE | re.DOTALL)
    m = p.search(source)
    if m and len(m.groups()) > 0:
        return m.group(group)
    return None


def find_href(source, pattern):
    '''Find the href attribute of an anchor tag whos text matches the given pattern'''
    links = BeautifulSoup.SoupStrainer('a')
    soup = BeautifulSoup.BeautifulSoup(source, links)
    linkText = soup.find(text = re.compile(pattern))
    if (linkText != None):
        link = linkText.findParent('a')
        return str(link['href'])
    #p = re.compile('<a .*href="([^"]*)".*>.*' + pattern + '.*</a>', re.IGNORECASE | re.DOTALL)
    #m = p.search(source)
    #if m and len(m.groups()) > 0:
    #    return m.group(1)
    return None

def find_text_in_response(patternBefore, patternAfter, pattern = '.*', group = 1):
    source = HTTPPluginControl.getHTTPUtilities().getLastResponse().getText()
    return find_text(source, patternBefore, patternAfter, pattern, group)

def find_href_in_response(pattern):
    source = HTTPPluginControl.getHTTPUtilities().getLastResponse().getText()
    return find_href(source, pattern)

def find_errors(source):
    soup = BeautifulSoup.BeautifulSoup(source)
    return soup.findAll('ul', 'errors')

def process_result():
    '''Process the result of the last request (if the result is text/html).
    if ecourt.checkAppErrors is set in grinder.properties, then it will check the page for any reported errors and if found will set the test to failed
    if ecourt.saveAllPages is set in grinder.properties, then it will save the resulting page
    '''
    lastResponse = HTTPPluginControl.getHTTPUtilities().getLastResponse()
    contentType = str(lastResponse.getHeader('Content-Type'))
    if (not contentType.startswith('text/html')):
        return
    # check for any errors in the page
    stats = grinder.statistics.forCurrentTest #@UndefinedVariable
    if (grinder.getProperties().getBoolean('ecourt.checkAppErrors', False)):
        source = lastResponse.getText()
        errors = find_errors(source)
        if (errors != None and len(errors) > 0):
            stats.setSuccess(0)
            write_to_file(source, stats.test.number, True)
    if (grinder.getProperties().getBoolean('ecourt.saveAllPages', False)):
        source = lastResponse.getText()
        write_to_file(source, stats.test.number)
        

