import urllib
from google.appengine.api import urlfetch
import logging

class GoogleAuthenticator:
    def authenticate(self,userId,passWd,appId,logintoken=None,logincaptcha=None):
            my_app_name = appId+'-1.0'
            users_email_address = userId
            users_password      = passWd

            auth_uri = 'https://www.google.com/accounts/ClientLogin'
            fieldContent = { "Email":   users_email_address,
                              "Passwd":  users_password,
                              "service": "ah",
                              "source":  my_app_name,
                              "accountType": "HOSTED_OR_GOOGLE" }
            if logintoken:
                fieldContent['logintoken'] = logintoken
                fieldContent['logincaptcha'] = logincaptcha
            authreq_data = urllib.urlencode(fieldContent)
            try:
                result = urlfetch.fetch(url=auth_uri, payload=authreq_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'})
                logging.info("status code == "+str(result.status_code))
                auth_resp_body = result.content
                if result.status_code == 200:
                    auth_resp_dict = dict(x.split("=")
                                          for x in auth_resp_body.split("\n") if x)
                    authtoken = auth_resp_dict["Auth"]

                    logging.info('Authenticated ' +users_email_address)
                    return {"result":True, "Auth":authtoken}
                else:
                    if result.status_code == 403 and auth_resp_body.__contains__("CaptchaToken="):
                        logintoken = ""
                        captchaurl = ""
                        for line in auth_resp_body.split("\n"):
                            if line:
                                nameValueList = line.split("=")
                                if len(nameValueList)>1:
                                    if nameValueList[0] == 'CaptchaToken':
                                        logintoken = nameValueList[1]
                                    elif nameValueList[0] == 'CaptchaUrl':
                                        captchaurl = "https://www.google.com/accounts/" + nameValueList[1] +"="+ nameValueList[2]
                        return {"result":False, "error":"Enter the correct password above and then type the characters you see in the picture below","logintoken":logintoken, "captchaurl":captchaurl}
                    else:
                        logging.info('Authentication Failed '+users_email_address+'. Reason: '+result.content)
                        return {"result":False, "error":"The username or password you entered is incorrect"}
            except Exception, e:
                logging.info('expection on login '+users_email_address+'. Reason: '+str(e))
                return {'result':False,"error":"The username or password you entered is incorrect"}