"""
Components for rendering detailed object data views.
"""
from .base import Component
from typing import Optional, Callable, Union


class Detail(Component):
    """
    A component that binds a specific object to its descendants' context.
    Often used to apply Alpine.js `x-data` scopes tightly to a context object.
    """
    def __init__(self, x_data: Optional[Union[str, Callable]] = None, **kwargs):
        super().__init__(**kwargs)
        self.x_data = x_data

    def render_html(self, **kwargs):
        value = self.get_value(**kwargs)

        x_data_attr = ""
        if self.x_data:
            if callable(self.x_data):
                x_data_value = self.x_data(value)
            else:
                x_data_value = self.x_data
            x_data_attr = f" x-data='{x_data_value}'"

        return f"<div id='{self.uid}'{x_data_attr}>{''.join([child.render(**{**kwargs, 'object': value}) for child in self.children])}</div>"
