import json
import re

from flask import Blueprint, Response, jsonify, render_template, url_for, request
from StageHubAPI import Api, Resource, app, ma, SQLAlchemyAutoSchema, reqparse
from StageHubAPI.model import Account
from StageHubAPI.response import ApiResponse

account_bp = Blueprint('account', __name__)
api = Api(account_bp)


class Schema(SQLAlchemyAutoSchema):
    class Meta:
        model = Account
        include_relationships = True
        include_fk = True
        load_instance = True


account_schema = Schema()
accounts_schema = Schema(many=True)


def parse_args():
    pass


class Accounts(Resource):
    def get(self):
        arguments = ['login', 'mail', 'id']
        for arg in request.args.keys():
            if arg not in arguments:
                return ApiResponse(message='Unknown argument : %s' % arg,
                                   objects=[],
                                   status=200).as_dict()

        login = request.args.get("login")
        mail = request.args.get("mail")
        aid = request.args.get("id")

        if login:
            result = Account.query.filter(Account.login.like(login))
            return account_schema.dump(result, many=True), 200

        if mail:
            result = Account.query.filter(Account.mail.like(mail))
            response = ApiResponse(message='Success',
                                   objects=account_schema.dump(result, many=True),
                                   status=200)
            return response.as_dict()

        if aid:
            result = Account.query.filter(Account.id == aid)
            response = ApiResponse(message='Success',
                                   objects=account_schema.dump(result, many=True),
                                   status=200)
            return response.as_dict()
            # return account_schema.dump(result, many=True), 200

        return accounts_schema.dump(Account.query.all(), many=True), 200

    def post(self, name):
        pass


class AccountByName(Resource):
    def get(self, name):
        if '@' in name:
            # Email filter
            result = Account.query.filter(Account.mail.like(name)).first()
        elif name.isdigit():
            result = Account.query.filter(Account.id == name).first()
        else:
            result = Account.query.filter(Account.login.like(name)).first()
        return account_schema.dump(result), 200


api.add_resource(Accounts, '/accounts')
api.add_resource(AccountByName, '/accounts/<string:name>')
