import logging

from google.appengine.api import users

from orangescape.model.server.Cookies import Cookies
from orangescape.model.server.Context import getApplication
from GAEAuth import GAEAbstractAuth

class OpenIdAuthenticator(GAEAbstractAuth):

    def authenticate(self, controller):
        #incase of openid authenticate method will never get invoked
        resultDict = {"authenticated":False}
        if users.get_current_user():
            resultDict["authenticated"] = True
            resultDict["userEmail"] = users.get_current_user().email()
        return resultDict

    def processLogin(self, controller):
        #incase of openid process Login method never get invoked
        self.renderLogin(self, controller)

    def renderLogin(self, controller):
        openid_url = controller.request.GET.get('openid')
        forward_url_obtained = self.getForwardUrl(controller)
        #for federated login sso
        if openid_url is None:
            queryString = controller.request.query_string
            params = controller.getQueryStringParams(queryString)
            openid_url = params.get("domain")

        if users.get_current_user():
            controller.redirect(forward_url_obtained)
        elif self.checkCookies(controller):
            cookies = Cookies(controller)
            if cookies.__contains__('odomain'):
                controller.redirect(users.create_login_url(forward_url_obtained, None, cookies['odomain']))
        elif not openid_url:
            logging.debug('rendering the login page: cookie and current user not available!')
            from RenderTemplate import renderTemplate
            templateDict = {'forwardUrl':forward_url_obtained}
            htmlStr = renderTemplate('openid_login.html',templateDict,controller)
            controller.response.out.write(htmlStr)
        else:
            cookies = Cookies(controller)
            cookies['odomain']=openid_url
            controller.redirect(users.create_login_url(forward_url_obtained, None, openid_url))

    def doPreRequest(self,controller):
        if users.get_current_user():
            return self.checkCookies(controller,users.get_current_user().email(),users.get_current_user().federated_provider())

    def getForwardUrl(self, controller):
        forward_url_obtained = controller.request.GET.get('forward')
        if not forward_url_obtained:
            forward_url_obtained = controller.request.GET.get('continue') or ''.join(['/',getApplication().getSheetId(),'/1/home'])
        return forward_url_obtained

    def getLogoutUrl(self):
        openid_provider_string = ""
        if users.get_current_user() and users.get_current_user().federated_provider():
            openid_provider_string='?openidprovider='+users.get_current_user().federated_provider()
        return users.create_logout_url(''.join(['/',getApplication().getSheetId(),'/1/signin',openid_provider_string]))
