""" module for auto generating schema from SQL alchemy models.
"""
# pylint: disable=E0611

from pydantic import BaseConfig

import sqlalchemy.orm
import sqlalchemy.sql.sqltypes
from pydantic_sqlalchemy import sqlalchemy_to_pydantic

from apifactory.database import Models


class OrmConfig(BaseConfig):
    """Simple helper config class.
    Required for correctly mapping SQL alchemy models to pydantic schemas.
    """

    orm_mode = True


class Schemas:
    """Creates pydantic schemas based on sqlalchemy models.
    These schemas are then used in FastAPI to convert sqlalchemy output to json
    and json input to input that is accepted to sqlalchemy.

    :param models: Models object generated by the DataBase class.
    :type models: Models


    Basic usage is instantiate a Database form api factory
    and acces the models atribute contained within.

    >>> from apifactory import DataBase
    >>> db = Database(
            database_url
        )
    >>> schemas = Schemas(db.models)

    """

    def __init__(self, models: Models) -> None:

        tables = [
            getattr(models, x)
            for x in dir(models)
            if (type(getattr(models, x)) == sqlalchemy.orm.decl_api.DeclarativeMeta)
        ]
        for table in tables:
            # disabled false positve pylint error
            # pylint: disable=C0103
            table_name = str(table.__table__.name)
            # pylint: enable=C0103
            schema = sqlalchemy_to_pydantic(table, config=OrmConfig)
            setattr(self, table_name, schema)
