from controllers.auth import *
from models import APIRole, APIUser
from flask_restful import Api
from werkzeug.utils import import_string


class Authentication(object):

    def __init__(self, app=None, url_prefix=None, **kwargs):
        self.app = app
        if app is not None:
            self.init_app(app, url_prefix)

    def init_app(self, app, url_prefix):
        self.setup_managers(app)

        auth = Api(app, prefix=url_prefix)
        auth.add_resource(RoleList, '/roles/')
        auth.add_resource(RoleDetail, '/roles/<path:pk>/')
        auth.add_resource(APIUserList, '/users/')
        auth.add_resource(APIUserDetail, '/users/<path:pk>/')

    def setup_managers(self, app):
        if not all(k in app.config for k in ('ROLE_MANAGER', 'APIUSER_MANAGER')):
            raise Exception('You need to define the managers.')

        APIRole.manager_class = import_string(app.config['ROLE_MANAGER'])
        APIUser.manager_class = import_string(app.config['APIUSER_MANAGER'])
