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

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('/')
async def homepage(request):
    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__':
    uvicorn.run(app, host='0.0.0.0', port=8000)