from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
from starlette.applications import Starlette
from starlette.templating import Jinja2Templates
from starlette.responses import JSONResponse, PlainTextResponse
from prediction import predict
import pyrebase
import uvicorn
import json

config = {
  "apiKey": "AIzaSyBrnRxGfzyWvLZu9XMUnbZTPpu8NxHBRE0",
  "authDomain": "softlab-ba722.firebaseapp.com",
  "databaseURL": "https://softlab-ba722.firebaseio.com",
  "projectId": "softlab-ba722",
  "storageBucket": "softlab-ba722.appspot.com",
  "messagingSenderId": "210803257141",
  "appId": "1:210803257141:web:f2fcb4e8d166ca9bc4a67c",
  "measurementId": "G-L85J7NJJZK"
}

firebase = pyrebase.initialize_app(config)
auth = firebase.auth()

scopes = [
  "https://www.googleapis.com/auth/userinfo.email",
  "https://www.googleapis.com/auth/firebase.database"
]
templates = Jinja2Templates(directory='templates')

app = Starlette(debug=True)
credentials = service_account.Credentials.from_service_account_file("./serviceKey.json", scopes=scopes)
authed_session = AuthorizedSession(credentials)


@app.route('/auth',methods=["POST"])
async def basic(request):
    body = await request.form()
    email = body['email']
    password = body['password']
    try:
        auth.sign_in_with_email_and_password(email, password)
        return templates.TemplateResponse('index.html', {'request': request})
    except:
        message = 'Please check your credentials'
    return templates.TemplateResponse('login.html', {'request': request, 's':message})

@app.route('/registration',methods=["POST"])
async def firebase_register(request):
    body = await request.form()
    email = body['email']
    password = body['pass1']
    confirm = body['pass2']
    if password!=confirm:
        message = 'Registration unsuccessful'
        return templates.TemplateResponse('register.html', {'request': request, 's':message})
    try:
        auth.create_user_with_email_and_password(email, password)
        message = 'Registration successful'
    except:
        message = 'Registration unsuccessful'
        return templates.TemplateResponse('register.html', {'request': request, 's':message})
    return templates.TemplateResponse('login.html', {'request': request, 's':message})


# @app.route('/register',methods=["POST"])
# async def registration(request):
#     body = await request.json()
#     email, password = body['email'],body['password']
#     json = { 
#         "email": email,
#         "password": password,
#         "returnSecureToken": True
#     }
#     message = "Success, Thanks for your envaluable contribution!"
#     response = authed_session.post("https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser",None,json)
#     print(response)
#     if response.status_code!=200:
#         message = "Oops some error occured please try after some time."
#     return PlainTextResponse(message)


@app.route('/')
async def login(request):
    return templates.TemplateResponse('login.html', {'request': request})

@app.route('/contribute')
async def contrbPage(request):
    return templates.TemplateResponse('contribute.html', {'request': request})

@app.route('/{prompt}')
async def getEssay(request):
    prompt = request.path_params['prompt']
    response = authed_session.get("https://softlab-ba722.firebaseio.com/"+prompt+".json")
    data = response.json().values()
    return templates.TemplateResponse('topic.html', {'request': request,'essayResponse':data,'topic':prompt})

# app.add_route('/evaluate', predict, methods=["POST"])
@app.route('/evaluate',methods=["POST"])
async def evaluate(request):
    body = await request.form()
    score = predict(body['essay'])
    return templates.TemplateResponse('score.html', {'request': request, 'score':score})

@app.route('/contribute',methods=["POST"])
async def evaluate(request):
    body = await request.form()
    score, essay, prompt = body['score'], body['essay'], body['prompt']
    json = { 
        "essay": essay,
        "score": score
    }
    message = "Success, Thanks for your envaluable contribution!"
    response = authed_session.post("https://softlab-ba722.firebaseio.com/"+prompt+"/.json",None,json)
    print(response)
    if response.status_code!=200:
        message = "Oops some error occured please try after some time."
    return templates.TemplateResponse('thanks.html', {'request': request, 'score':score, 'message':message, 'essay':essay})

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8040)