import gdata.alt.appengine
import gdata.auth
import gdata.service 
import gdata.health
import gdata.health.service
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import os, re, time, string
import urllib2, logging, base64
import simplejson

H9_AUTHSUB_HANDLER = 'https://www.google.com/h9/authsub'
H9_SCOPE = 'https://www.google.com/h9/feeds/'
H9_NEXT_URI = 'https://chiefmedicalofficer.appspot.com/authsub'
AUTHSUB_PARMS = '&permission=1'
if os.environ.get('SERVER_SOFTWARE','').startswith('Devel'):
   H9_NEXT_URI = 'http://localhost:8106/authsub'
   AUTHSUB_PARMS = '&secure=0&permission=1&session=1'
else:
   H9_NEXT_URI = 'https://chiefmedicalofficer.appspot.com/authsub'

GDATA_RESOURCE = "https://www.google.com/health/feeds/profile/default"
ACCESS_TOKEN_SETTINGS_URL = 'https://www.google.com/health/AuthenticationTokenSettings'
    
from keys import H9_RSA_KEY 

from base import BaseRequestHandler, GoogleHealthConnect
from handlers import * 
from ghealth import *

healthConn = GoogleHealthConnect()

class AuthSubURLRequestHandler(BaseRequestHandler):
    def get(self):
        self.response.out.write(self.get_authsub_uri())

class AuthSubLoginHandler(BaseRequestHandler):
    def get(self):
        view_vals = self.get_view_defaults()
        token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri, rsa_key=H9_RSA_KEY) 
        if token:
            # token is of class SecureAuthSubToken
            healthConn.client.UpgradeToSessionToken(token)
        else:
            logging.warn("No token found in url")
            pass
        access_token = healthConn.client.token_store.find_token(H9_RSA_KEY)
        logging.warn("Token store has %s"%access_token) 
        if not True: #access_token.valid_for_scope(H9_RSA_KEY):
            user = users.get_current_user()
            authsuburi = self.get_authsub_uri()
            self.render_response('index_public', {'login_url': authsuburi, 'username':user.nickname()})          
        else: 
            self.response.out.write(access_token)
            if access_token and users.get_current_user():
              healthConn.client.token_store.add_token(access_token)
            elif access_token:
              healthConn.client.current_token = access_token
              healthConn.logged_in = True
              #healthConn.client.SetOAuthToken(access_token)
            self.redirect('/ccr')   
            
class ShowCCRHandler(BaseRequestHandler):
    def get(self):  
        view_vals = healthConn.getCCR(self.get_view_defaults())
        self.logged_in = True 
        self.render_response('conditions', view_vals)

class ShowTestResultHandler(BaseRequestHandler):
    def get(self):  
        view_vals = healthConn.getTestResults(self.get_view_defaults())
        self.logged_in = True 
        self.render_response('tests', view_vals)
                                                                         
class ShowProfileHandler(BaseRequestHandler):
    def get(self):  
        view_vals = healthConn.getProfile(self.get_view_defaults())
        self.logged_in = True 
        self.render_response('profiles', view_vals)

        
        
def main():

    urls = [('/', ShowPublicHandler),
            ('/authsub', AuthSubLoginHandler), 
            ('/ccr', ShowCCRHandler),
            ('/conditions', ShowCCRHandler),
            ('/tests', ShowTestResultHandler),
            ('/profiles', ShowProfileHandler),
            ('/index_public', ShowPublicHandler), 
            ('/logout', LogoutHandler),
            ('/maps', MapHandler),
            ('/browse', BrowseHandler), 
            ('/mobile', MobileHandler),
            ('/about', AboutHandler),
            ('/getauthsuburl', AuthSubURLRequestHandler),
            
           ]
    
    application = webapp.WSGIApplication(urls, debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
