"""Byte layouts for ``omfi:*`` types -- the field maps the raw view highlights.

Each layout describes how to carve a value's bytes into named ranges, the way a
protocol dissector carves a packet.  They are *declarative* rather than code so
that the same table can be shipped to the browser and rendered without
re-implementing any decoding: Python decides what the fields are, JavaScript
only draws them.

Two shapes::

    {"kind": "fixed",  "fields": [[offset, size, label, fmt, note], ...]}
    {"kind": "array",  "header": [...], "stride": n, "fields": [...],
     "record": "label"}

``fmt`` is a hint for how the browser should render the slice, not a decoder:
``u8 u16 u32 i32 i64 hex ascii utf8``.  A size of ``-1`` means "to the end of
the value".

Notes are for facts about the data, not for explanation.  The UI is a field
list, not a tutorial: a note earns its place only when the field's name does
not already say what it is.

The authority for these is :mod:`mdb.datatypes` -- if a decoder there changes,
the layout here is what has to follow.  Where a layout would only restate "the
whole value is one integer" it is omitted; the browser falls back to a single
span labelled with the type name.
"""
from __future__ import annotations

__all__ = ["LAYOUTS", "TOC_ENTRY_LAYOUT", "CONTAINER_LABEL_LAYOUT", "layout_for"]


def _fixed(*fields):
    return {"kind": "fixed", "fields": [list(f) for f in fields]}


def _array(stride, fields, record="record", count_size=2):
    return {
        "kind": "array",
        "header": [[0, count_size, "count", "u%d" % (count_size * 8),
                    "number of records that follow"]],
        "start": count_size,
        "stride": stride,
        "record": record,
        "fields": [list(f) for f in fields],
    }


#: The 24-byte TOC entry.  Not an ``omfi:`` type -- this is Bento's own record.
#: Every field is resolved against the file before display, so none of them
#: carry notes.
TOC_ENTRY_LAYOUT = _fixed(
    [0, 4, "objectID", "u32", ""],
    [4, 4, "propertyID", "u32", ""],
    [8, 4, "typeID", "u32", ""],
    [12, 4, "value", "u32", ""],
    [16, 4, "length", "u32", ""],
    [20, 4, "gen/flags", "u32", ""],
)

#: The 24 bytes at EOF-24: the Bento container label.
CONTAINER_LABEL_LAYOUT = _fixed(
    [0, 8, "magic", "hex", ""],
    [8, 2, "flags", "u16", ""],
    [10, 2, "byteOrder", "ascii", ""],
    [12, 2, "majorVersion", "u16", ""],
    [14, 2, "minorVersion", "u16", ""],
    [16, 4, "tocOffset", "u32", ""],
    [20, 4, "tocSize", "u32", ""],
)

LAYOUTS = {
    # -- identity ---------------------------------------------------------
    # 32-byte SMPTE UMID.  The 12-byte short-UID form is handled separately
    # because omfi:UID carries both and only length tells them apart.
    "omfi:UID/32": _fixed(
        [0, 12, "universalLabel", "hex", "SMPTE 330M"],
        [12, 1, "materialNumberLength", "u8", ""],
        [13, 1, "instanceHigh", "u8", ""],
        [14, 1, "instanceMid", "u8", ""],
        [15, 1, "instanceLow", "u8", ""],
        [16, 8, "materialNumber", "hex", "matches the short UID"],
        [24, 8, "materialGUIDRest", "hex", ""],
    ),
    "omfi:UID/12": _fixed(
        [0, 4, "prefix", "u32", ""],
        [4, 4, "major", "u32", ""],
        [8, 4, "minor", "u32", ""],
    ),
    "omfi:GUID": _fixed(
        [0, 4, "Data1", "u32", ""],
        [4, 2, "Data2", "u16", ""],
        [6, 2, "Data3", "u16", ""],
        [8, 8, "Data4", "hex", ""],
    ),

    # -- aggregates -------------------------------------------------------
    "omfi:ObjRef": _fixed(
        [0, 8, "objectID", "i64", "64-bit; only the low word is populated"],
    ),
    "omfi:ObjRefArray": _array(8, [
        [0, 8, "objectID", "i64", ""],
    ], record="ref"),
    # 12 + 4 + 4, NOT 12 + 8: reading the reference as 64-bit silently
    # corrupts every CompositionMobs lookup, because `extra` is non-zero there.
    "omfi:MobIndex": _array(20, [
        [0, 12, "shortUID", "hex", ""],
        [12, 4, "objectID", "u32", "32-bit, not 64"],
        [16, 4, "extra", "u32", "unknown"],
    ], record="entry"),
    "omfi:Int32Array": _array(4, [[0, 4, "value", "i32", ""]],
                              record="value", count_size=0),

    # -- rates and time ---------------------------------------------------
    "omfi:ExactEditRate": _fixed(
        [0, 4, "numerator", "i32", ""],
        [4, 4, "denominator", "i32", ""],
    ),
    "omfi:Rational": _fixed(
        [0, 4, "numerator", "i32", ""],
        [4, 4, "denominator", "i32", ""],
    ),
    "omfi:TimeStamp": _fixed(
        [0, 4, "seconds", "u32", "Unix, UTC"],
        [4, 1, "flag", "u8", ""],
    ),
    "omfi:VersionType": _fixed(
        [0, 1, "major", "u8", ""],
        [1, 1, "minor", "u8", ""],
    ),

    # -- text -------------------------------------------------------------
    "omfi:String": _fixed([0, -1, "text", "utf8", ""]),
    "omfi:ObjectTag": _fixed([0, -1, "fourCC", "ascii", ""]),
}

#: Types whose whole value is one scalar; the browser labels the single span
#: with the type name and needs no table entry.
SCALAR_FORMATS = {
    "omfi:Char": "i8", "omfi:Uchar": "u8",
    "omfi:Short": "i16", "omfi:Ushort": "u16",
    "omfi:Long": "i32", "omfi:Ulong": "u32",
    "omfi:Int32": "i32", "omfi:UInt32": "u32",
    "omfi:Int64": "i64", "omfi:UInt64": "u64",
    "omfi:Boolean": "u8", "omfi:Double": "f64", "omfi:Float": "f32",
    "omfi:AttrKind": "u16", "omfi:TrackType": "u16",
    "omfi:PhysicalMobType": "u16", "omfi:UsageCodeType": "u32",
    "omfi:ColorSitingType": "u16", "omfi:LayoutType": "u16",
    "omfi:EdgeType": "u16", "omfi:CharSetType": "u16",
    "omfi:JPEGTableIDType": "u32",
}


def layout_for(type_name: str, length: int):
    """The layout key for a value, or ``None`` when the type is opaque.

    ``omfi:UID`` is the one type whose shape depends on its length, so the key
    it returns is suffixed.
    """
    if type_name == "omfi:UID":
        key = "omfi:UID/%d" % length
        return key if key in LAYOUTS else None
    return type_name if type_name in LAYOUTS else None
