# -*- coding: utf-8 -*-

import io
import json
import os

from flask_api_auth.models import APIUser, APIRole


BASE_DIR = os.path.dirname(__file__)
fixtures = {}


def reader(path):
    with io.open(path, 'r', encoding='utf-8') as fh:
        return fh.read()


def get_json(fixture):
    path = os.path.join(BASE_DIR, 'fixtures', fixture)

    if not fixtures.get(path):
        fixtures[path] = reader(path)

    return json.loads(fixtures[path])


def get_stored_role_data():
    return get_json('role_stored_data.json')


def get_stored_apiusers_data():
    return get_json('apiuser_stored_data.json')


def get_instance_by_name(model_class, name):
    items = {'APIUser': get_stored_apiusers_data,
             'APIRole': get_stored_role_data}[model_class.__name__]

    generator = (item for item in items() if item['name'] == name)
    return model_class(next(generator, None), validate=False)


def get_stored_user(name):
    return get_instance_by_name(APIUser, name)


def get_stored_role(name):
    return get_instance_by_name(APIRole, name)
