# Copyright 2025 Acute Technology Inc. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
"""I2C 32-bit Register Target Class."""

from enum import IntEnum
from typing import TYPE_CHECKING, ClassVar

from aqpxlib.abstract import PxAbstractTarget

if TYPE_CHECKING:
    from aqpxlib.toplevel import AqProtocolExerciser

from aqpxlib.message import I2C32BitRegisterTargetConfig as PxI2C32BitRegisterTargetConfig
from aqpxlib.message import I2C32BitRegisterTargetConfigSubAddressType
from aqpxlib.message import I2C32BitRegisterTargetState as PxI2C32BitRegisterTargetState


class PxI2C32BitRegisterTarget(PxAbstractTarget):
    """I2C Base Target Class."""

    # Used to identify the class
    identifier: str = "i2c_32bit_register_target"
    protobuf_key: str = "i2_c_32_bit_reg_target"
    valid_buses: ClassVar[list[str]] = ["i3c", "i2c"]

    class SubAddressType(IntEnum):
        """Sub-address type enumeration.

        This is intended to avoid exporting protobuf enum to the interface.
        """

        NONE = I2C32BitRegisterTargetConfigSubAddressType.SUB_ADDR_NONE
        REPEAT = I2C32BitRegisterTargetConfigSubAddressType.SUB_ADDR_8BIT_REPEAT
        IGNORE = I2C32BitRegisterTargetConfigSubAddressType.SUB_ADDR_8BIT_IGNORE
        INCREMENT = I2C32BitRegisterTargetConfigSubAddressType.SUB_ADDR_8BIT_INCREMENT
        INCREMENT_WITH_LOOP = I2C32BitRegisterTargetConfigSubAddressType.SUB_ADDR_8BIT_INCREMENT_WITH_LOOP

    def __init__(
        self,
        exerciser: "AqProtocolExerciser",
        address: int = 0,
        sub_address_type: SubAddressType = SubAddressType.NONE,
        config: PxI2C32BitRegisterTargetConfig | None = None,
        *args,
        **kwargs,
    ) -> None:
        """Initialize an I2C 32-bit register target."""
        if config is None:
            config = PxI2C32BitRegisterTargetConfig(
                address=address,
                sub_address_type=sub_address_type,
            )

        super().__init__(exerciser, config=config, *args, **kwargs)

    @property
    def address(self) -> int:
        """Static address of the device."""
        return self.config.address

    @property
    def sub_address_type(self) -> SubAddressType:
        """Sub-address type of the device."""
        return self.SubAddressType(self.config.sub_address_type.value)

    @property
    def register_value(self) -> int:
        """Get the register value of the target."""
        state = self.state
        assert isinstance(state, PxI2C32BitRegisterTargetState)
        return state.reg_value

    @register_value.setter
    def register_value(self, value: int) -> None:
        """Set the register value of the target."""
        self._set_state(PxI2C32BitRegisterTargetState(reg_value=value))


__all__ = [
    "PxI2C32BitRegisterTarget",
    "PxI2C32BitRegisterTargetConfig",
    "PxI2C32BitRegisterTargetState",
]
