#  Copyright (C) 2023
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Mike Orlov <m.orlov@abm-jsc.ru>
import copy
from dataclasses import Field
from logging import getLogger
from typing import Callable

import sqlalchemy
import sqlalchemy.orm
from type_cast import get_dataclass_field_name_to_field

from entity_read.entity import Entity
from entity_read.entity_field import get_sqlalchemy_metadata
from ..utils.no_default import NoDefault

logger = getLogger(__name__)


class _DeleteViewMixin:
    @classmethod
    def _produce_field_name_to_field(cls, related_entity_type: type[Entity],
                                     relation_remote_column: sqlalchemy.Column = None) -> dict[str, Field | Callable]:
        field_name_to_field = copy.copy(get_dataclass_field_name_to_field(related_entity_type))
        result = {}
        for field_name, field in field_name_to_field.items():
            field_copy = copy.copy(field)
            sql_alchemy_property = get_sqlalchemy_metadata(field)

            if isinstance(sql_alchemy_property, sqlalchemy.orm.RelationshipProperty):
                continue
            elif isinstance(sql_alchemy_property, sqlalchemy.Column):
                column: sqlalchemy.Column = sql_alchemy_property
                if not column.primary_key:
                    continue
                if relation_remote_column is not None and column == relation_remote_column:
                    field_copy.init = False
                    field_copy.default = NoValue
                else:
                    field_copy.default = NoDefault
            else:
                logger.warning(f"ignored attribute: {field}, cos {sql_alchemy_property} has unexpected type")

            result[field_name] = field_copy

        result['entity_type'] = related_entity_type
        return result
