import os
import posixpath
from datetime import datetime

from nabu.io.utils import get_first_hdf5_entry, get_h5_value
from tomoscan.io import HDF5File

path = os.path


def get_h5obj_value(h5_obj, name, default=None):
    if name in h5_obj:
        return h5_obj[name][()]
    return default


def get_string(str_or_bytes):
    if isinstance(str_or_bytes, bytes):
        return str_or_bytes.decode()
    return str_or_bytes


def format_time(timestamp_str):
    try:
        d = datetime.fromisoformat(timestamp_str)
    except ValueError:
        if timestamp_str.endswith("Z"):
            # https://docs.python.org/3/library/datetime.html#technical-detail
            # providing 'Z' is identical to '+00:00'
            timestamp_str = timestamp_str.replace("Z", "+00:00")
            d = datetime.fromisoformat(timestamp_str)
    return d.isoformat()  # long format


def get_datetime(date_str):
    if date_str is None:
        return None
    try:
        date = format_time(date_str)
    except Exception:
        print("Could not parse timestamp %s" % date_str)
        date = None
    return date


def is_same_config(fname, ai_config):
    entry = get_first_hdf5_entry(fname)
    aiconfig_path = posixpath.join(
        entry,
        "azimuthal integration",
        "configuration",
        "ai_config",
    )
    file_aiconfig = get_string(
        get_h5_value(fname, aiconfig_path, default_ret=None) or "",
    )
    return file_aiconfig == str(ai_config)


def guess_detector_name(fname, entry):
    with HDF5File(fname, "r") as f:
        meas = f[entry]["measurement"]
        for k in meas:
            if hasattr(meas[k], "ndim") and meas[k].ndim == 3:
                return k
    return None
