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 uvicorn
import json
import os

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

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


@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 homepage(request):
    print('fmakmf')
    return templates.TemplateResponse('index.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")
    return JSONResponse(response.json())


# 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 PlainTextResponse(message)

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    uvicorn.run(app, host='0.0.0.0', port=port)