from orangescape.model.server.SystemInterface import Auth
import urllib, base64, uuid, os, logging
from orangescape.model.server.Context import getApplication
from orangescape.model.server.UserAuthentication import UserAuthentication
from orangescape.model.server.Cookies import Cookies
from google.appengine.api import memcache

class GAEAbstractAuth(Auth):
    def checkCookies(self, controller, userEmail=None, domain=None):
        cookies = Cookies(controller)
        if cookies.__contains__('sessionid') and memcache.get(cookies['sessionid']):
            sessionId=cookies['sessionid']
            userSurrogateId=str(base64.b64decode(memcache.get(sessionId))).strip()
            memcache.set(sessionId,memcache.get(sessionId))
            os.environ['USER_ID']=userSurrogateId #TODO Why this is done?
            return userSurrogateId
        elif userEmail:
            uniqueId=str(uuid.uuid1())
            cookies['sessionid'] = uniqueId
            userinitialization=UserAuthentication(controller.session,userEmail)
            userSurrogateId=userinitialization.authenticateUser()
            cookies['userid'] = userSurrogateId
            memcache.add(uniqueId, str(base64.b64encode(userSurrogateId)))
            return userSurrogateId
        else:
            return None

    def processLogin(self, controller):
        resultDict = self.authenticate(controller)
        if resultDict.get("authenticated"):
            forwardUrl=self.getForwardUrl(controller)
            userEmail = resultDict.get("userEmail")
            userSurrogateId=self.checkCookies(controller, userEmail)
            controller.redirect(urllib.unquote(forwardUrl))
        else:
            self.renderLogin(self,controller)

    def renderLogin(self,controller):
        forwardUrl=self.getForwardUrl(controller)
        if self.checkCookies(controller):
            controller.redirect(urllib.unquote(forwardUrl))
        else:
            from RenderTemplate import renderTemplate
            templateDict = {'forwardUrl':forwardUrl}
            htmlStr = renderTemplate("login.html",templateDict,controller)
            controller.response.out.write(htmlStr)

    def doPreRequest(self,controller):
        return self.checkCookies(controller)

    def getForwardUrl(self, controller):
        forwardUrl=controller.request.get("forward")
        if len(forwardUrl)==0:
                forwardUrl="/"+getApplication().getSheetId()+"/1/home"
        return forwardUrl

    def getLogoutUrl(self):
        logout_url_list=['/',getApplication().getSheetId(),'/1/signin']
        return ''.join(logout_url_list)