from orangescape.model.server.Context import getApplication
from orangescape.model.server.SystemInterface import Auth
from orangescape.model.server.UserAuthentication import UserAuthentication
import urllib,logging

class EnterpriseAbstractAuth(Auth):
    def processLogin(self, controller):
        resultDict = self.authenticate(controller)
        if resultDict.get("authenticated"):
            forwardUrl=self.getForwardUrl(controller)
            userEmail = resultDict.get("userEmail")
            userinitialization=UserAuthentication(controller.session,userEmail)
            userSurrogateId=userinitialization.authenticateUser()
            controller.redirect(urllib.unquote(forwardUrl))
        else:
            self.renderLogin(self,controller)


    def renderLogin(self,controller):
        forwardUrl=self.getForwardUrl(controller)
        session = controller.session
        if session.getUser():
            logging.warn('while logging in session has user called %s'%(session.getUser().getSheetId()))
            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):
        session = controller.session
        if session.getUser():
            return session.getUser().getSheetId()
        else:
            currentUrl=urllib.quote(controller.request.path+"?"+controller.request.query_string)
            controller.redirect("/"+getApplication().getSheetId()+"/1/signin/?forward="+currentUrl,True)
            return False

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

    def getLogoutUrl(self):
        dev_logout_url = '/'+getApplication().getSheetId()+'/1/logout'
        return dev_logout_url