#!/usr/bin/python
import httplib, urllib, re

__all__ = ["runExpertCocomo2000"]

def createParameters (cocomo_values):
    '''Creates parameters for runExperCocomo based on cocomo_values map'''
    #order of these matter
    return urllib.urlencode([
        ('new', cocomo_values['kloc']*1000),
        ('reused', ''),
        ('DM_reused', 0),
        ('CM_reused', 0),
        ('IM_reused', ''),
        ('AA_reused', ''),
        ('modified', ''),
        ('DM_modified', ''),
        ('CM_modified', ''),
        ('IM_modified', ''),
        ('AA_modified', ''),
        ('SU_modified', ''),
        ('UNFM_modified', ''),
        ('prec', cocomo_values['prec']-1),
        ('flex', cocomo_values['flex']-1),
        ('resl', cocomo_values['resl']-1),
        ('team', cocomo_values['team']-1),
        ('pmat', cocomo_values['pmat']-1),
        ('rely', cocomo_values['rely']-1),
        ('data', cocomo_values['data']-1),
        ('cplx', cocomo_values['cplx']-1),
        ('ruse', cocomo_values['ruse']-1),
        ('docu', cocomo_values['docu']-1),
        ('time', cocomo_values['time']-1),
        ('stor', cocomo_values['stor']-1),
        ('pvol', cocomo_values['pvol']-1),
        ('acap', cocomo_values['acap']-1),
        ('pcap', cocomo_values['pcap']-1),
        ('pcon', cocomo_values['pcon']-1),
        ('aexp', cocomo_values['aexp']-1),
        ('pexp', cocomo_values['pexp']-1),
        ('ltex', cocomo_values['ltex']-1),
        ('tool', cocomo_values['tool']-1),
        ('site', cocomo_values['site']-1),
        ('sced', cocomo_values['sced']-1),
        ('submit', "Submit")
        ])


def runExpertCocomo2000(cocomo_values):
    '''Calls USC COCOMO2000 Expert with specified cocomo_values map.  Returns map with scores: effort, months, threats'''
    params = createParameters(cocomo_values)
    headers = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "text/html"}
    conn = httplib.HTTPConnection("sunset.usc.edu:80")
    conn.request("POST", "/cgi-bin/expert_cocomo2000", params, headers)
    response = conn.getresponse()
    #check valid reponse
    #print response.status, response.reason
    data = response.read()    
    conn.close
    #TODO check data for error before trying to parse
    effort=float(re.compile('(\d*\.\d*) Person-months').search(data).group(1))
    months=float(re.compile('(\d*\.\d*) Months').search(data).group(1))
    #threats=float(re.compile('Total Project Risk  </h3></TH><TH><IMG ALIGN=bottom SRC=http://sunset.usc.edu/research/COCOMOII/expert_cocomo/\d*.gif> </TH><TH>  (\d*\.\d*)</TH>').search(data).group(1))
    threats=float(re.compile('<TH>\s*<h3>\s*Total Project Risk\s*</h3></TH>\s*<TH>\s*<IMG ALIGN=bottom SRC=http://sunset.usc.edu/research/COCOMOII/expert_cocomo/\d*.gif>\s*</TH>\s*<TH>\s*(\d*\.\d*)\s*</TH>').search(data).group(1))
    return {    
            'effort': effort,
            'months': months,
            'threats':threats
            }
