# ext/declarative/clsregistry.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Routines to handle the string class registry used by declarative.

This system allows specification of classes and expressions used in
:func:`_orm.relationship` using strings.

"""
import weakref

from . import attributes
from . import interfaces
from .descriptor_props import SynonymProperty
from .properties import ColumnProperty
from .util import class_mapper
from .. import exc
from .. import inspection
from .. import util
from ..sql.schema import _get_table_key

# strong references to registries which we place in
# the _decl_class_registry, which is usually weak referencing.
# the internal registries here link to classes with weakrefs and remove
# themselves when all references to contained classes are removed.
_registries = set()


def add_class(classname, cls, decl_class_registry):
    """Add a class to the _decl_class_registry associated with the
    given declarative class.

    """
    if classname in decl_class_registry:
        # class already exists.
        existing = decl_class_registry[classname]
        if not isinstance(existing, _MultipleClassMarker):
            existing = decl_class_registry[classname] = _MultipleClassMarker(
                [cls, existing]
            )
    else:
        decl_class_registry[classname] = cls

    try:
        root_module = decl_class_registry["_sa_module_registry"]
    except KeyError:
        decl_class_registry[
            "_sa_module_registry"
        ] = root_module = _ModuleMarker("_sa_module_registry", None)

    tokens = cls.__module__.split(".")

    # build up a tree like this:
    # modulename:  myapp.snacks.nuts
    #
    # myapp->snack->nuts->(classes)
    # snack->nuts->(classes)
    # nuts->(classes)
    #
    # this allows partial token paths to be used.
    while tokens:
        token = tokens.pop(0)
        module = root_module.get_module(token)