import ctypes
from .enums import Zoom, SarMapOrientation

import Grifo_E_1553lib.data_types.enum_map as em

em.ENUM_MAP.update({
    "zoom_tellback": Zoom,
    "sar_map_orientation_tellback": SarMapOrientation,
})

class _RdrFunAndParam2TellbackStr(ctypes.LittleEndianStructure):
    _pack_ = 1
    _fields_ = [
        ("spare6_15", ctypes.c_uint16, 6),        # bit 0-5
        ("sar_spoi_feasibility", ctypes.c_uint16, 1),  # bit 6
        ("sar_crs_feasibility", ctypes.c_uint16, 1),   # bit 7
        ("sar_map_orientation_tellback", ctypes.c_uint16, 2),  # bit 8-9
        ("zoom_tellback", ctypes.c_uint16, 2),                # bit 10-11
        ("spare0_4", ctypes.c_uint16, 4),         # bit 12-15
    ]


class RdrFunAndParam2Tellback(ctypes.Union):
    _fields_ = [
        ("raw", ctypes.c_uint16),
        ("str", _RdrFunAndParam2TellbackStr)
    ]

    # Bitfield accessors for zoom tellback (bit 10-11)
    def get_zoom_tellback(self):
        return Zoom((self.raw >> 10) & 0x03)

    def set_zoom_tellback(self, value):
        self.raw &= ~(0x03 << 10)
        self.raw |= (value << 10)

    # Bitfield accessors for sar_map_orientation tellback (bit 8-9)
    def get_sar_map_orientation_tellback(self):
        return SarMapOrientation((self.raw >> 8) & 0x03)

    def set_sar_map_orientation_tellback(self, value):
        self.raw &= ~(0x03 << 8)
        self.raw |= (value << 8)

    # Bitfield accessors for SAR feasibility tellbacks
    def get_sar_crs_feasibility(self):
        return bool((self.raw >> 7) & 0x01)

    def set_sar_crs_feasibility(self, value):
        self.raw &= ~(0x01 << 7)
        self.raw |= (int(bool(value)) << 7)

    def get_sar_spoi_feasibility(self):
        return bool((self.raw >> 6) & 0x01)

    def set_sar_spoi_feasibility(self, value):
        self.raw &= ~(0x01 << 6)
        self.raw |= (int(bool(value)) << 6)