from flask import session
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from app.model import getUser


class LoginAPI(Resource):
    """
        Login Api Resource
    """

    def post(self):
        parser = RequestParser()
        parser.add_argument('email', required=True, help="Email cannot be blank!")
        parser.add_argument('password', required=True, help="Password cannot be blank!")
        args = parser.parse_args()

        if "user" in session and session["user"] is not None:
            return {'AUTH_RESULT': 'ALREADY_LOGGED'}, 201

        user = getUser(email=args['email'])

        if user is not None and args['password'] == args['email']:
            session['user'] = user
            return {'AUTH_RESULT': 'OK'}, 200
        else:
            session['user'] = None
            return {'AUTH_RESULT': 'AUTHENTICATION_FAILED'}, 401

    def delete(self):
        session['user'] = None
        return {'AUTH_RESULT': 'OK'}, 200

