import logging
import time
from typing import Any

from p4p.nt.enum import ntenum
from p4p.nt.ndarray import ntndarray
from p4p.nt.scalar import ntbool, ntfloat, ntint, ntnumericarray, ntstr, ntstringarray

logger = logging.getLogger(__name__)


class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.end = time.perf_counter()
        self.duration = self.end - self.start


def unwrap_p4p_structure(res: Any) -> Any:
    """
    Unwraps P4P structures to get clean Python types.
    """
    raw_data = res.raw
    raw_dict = raw_data.todict()
    # logger.debug("Unwrapping object type: %s", type(res))
    if isinstance(res, (ntbool, ntint, ntfloat, ntnumericarray, ntstr, ntstringarray)):
        val = raw_dict["value"]
    elif isinstance(res, ntenum):
        val = raw_dict["value"]["index"]
    elif isinstance(res, ntndarray):
        val = raw_dict["value"]
    else:
        val = None

    # logger.debug("Extracted %s from %s", val, raw_dict)
    return val
