"""AVBrowse's reader: pyavb on one side, a JSON-shaped answer on the other.

This module is the whole Python half of AVBrowse.  It runs unchanged under
CPython and under Pyodide -- nothing here imports a C extension, touches the
filesystem, or assumes a display.

The design follows the Qt inspector this app is a port of.  That tool was
lazy: a tree node held a Python value and only asked what its children were
when someone expanded it.  A browser cannot hold a Python value, so the
lazy-node idea survives as a *handle* -- a short string the JavaScript side
passes back to ask the next question.

    open_file(data, name)   ->  meta
    index()                 ->  census, classes, mob roots, labels, referrers
    node(handle)            ->  one object's properties, grouped
    children(handle)        ->  one node's children, for the raw tree

Two passes, and only two.  `index()` reads every object once and keeps a small
summary of each -- the class, the label, the MobID, what it points at.  It
does not keep the objects: pyavb's object cache is weak, so an object read
during the index pass is collected as soon as the pass moves on, and re-read
from its recorded file position when a user actually selects it.  That is what
keeps a 40 MB bin from becoming 40 MB of live Python objects plus a JSON copy
of the same thing in the browser.

Property *values* are formatted here and shipped as display strings.  The
browser re-decodes nothing semantic: turning a MobID into eight dotted groups
is a claim about SMPTE ST 330, and claims live on this side of the wall.
"""

from __future__ import (
    unicode_literals,
    absolute_import,
    print_function,
    division,
    )

import io
import datetime

import avb
from avb import mobid as _mobid
from avb import trackgroups as _trackgroups

MODEL_VERSION = 2

try:
    unicode
except NameError:                                    # pragma: no cover - py3
    unicode = str

try:
    long
except NameError:                                    # pragma: no cover - py3
    long = int

_INTS = (int, long)


# --------------------------------------------------------------- formatting

# How much of a long string survives into a grid cell.  The full value is
# still available through Copy; this is only what is drawn.
_TEXT_CAP = 300

# A bytearray is shown by its size rather than its contents.  The Qt tool did
# the same and for the same reason: a 19,000-byte blob rendered as hex is not
# information, it is a wall.
_PEEK = 16


def _fourcc(class_id):
    """b'MOBJ' -> 'MOBJ'.  None for the helper classes that have no ID."""
    if not class_id:
        return ''
    if isinstance(class_id, bytes):
        try:
            return class_id.decode('ascii')
        except Exception:
            return repr(class_id)
    return unicode(class_id)


def _is_object(value):
    return isinstance(value, avb.core.AVBObject)


def _class_name(value):
    return value.__class__.__name__


def _hexdump(data, limit=_PEEK):
    return ' '.join('%02x' % b for b in bytearray(data[:limit]))


def pretty_value(value):
    """One value -> (kind, text, note).

    `kind` is what the browser styles on; `text` is what it prints; `note` is
    the dimmed aside after it.  The kinds are deliberately few -- the grid has
    one look per kind and a kind nobody styles differently is a kind that did
    not need to exist.
    """
    if value is None:
        return 'empty', '-', ''

    if isinstance(value, (bytes, bytearray)):
        return ('blob', 'bytearray(%d)' % len(value),
                _hexdump(value) + ('...' if len(value) > _PEEK else ''))

    if isinstance(value, bool):
        return 'bool', 'true' if value else 'false', ''

    if isinstance(value, _INTS):
        # Anything that could be a 4CC or a flag word is worth showing twice.
        if abs(value) > 9999:
            return 'num', unicode(value), '0x%x' % (value & 0xFFFFFFFFFFFFFFFF)
        return 'num', unicode(value), ''

    if isinstance(value, float):
        return 'num', repr(value), ''

    if isinstance(value, _mobid.MobID):
        # Already dotted 32-bit groups, which is the point of printing it
        # this way: a 64-character hex run cannot be compared by eye.
        return 'id', unicode(value), ''

    if isinstance(value, datetime.datetime):
        return 'date', value.strftime('%Y-%m-%d %H:%M:%S'), ''

    if isinstance(value, datetime.date):
        return 'date', value.strftime('%Y-%m-%d'), ''

    if _is_object(value):
        cc = _fourcc(value.class_id)
        return ('object', _class_name(value), ('[%s]' % cc) if cc else '')

    if isinstance(value, list):
        return 'list', 'list (%d)' % len(value), ''

    if isinstance(value, dict):
        return 'dict', 'dict (%d)' % len(value), ''

    text = unicode(value)
    if len(text) > _TEXT_CAP:
        return 'str', text[:_TEXT_CAP], '(%d chars)' % len(text)
    return 'str', text, ''


def _type_name(pdef):
    """The declared type of a property, as pyavb spells it."""
    if pdef is None:
        return ''
    t = getattr(pdef, 'type', None)
    if t is None:
        return ''
    return unicode(t)


# ----------------------------------------------------------------- children

def _expandable(value):
    """Does this value have anything underneath it worth a twisty?

    An empty list is not expandable.  Neither is a scalar.  Everything the Qt
    tool would have called `setup()` on and found children in, is.
    """
    if _is_object(value):
        return len(value.property_data) > 0
    if isinstance(value, (list, dict)):
        return len(value) > 0
    return False


def object_properties(obj):
    """(key, value) for every property the object actually carries.

    Straight from the Qt tool: walk `propertydefs` in declaration order and
    skip the ones `property_data` has no entry for.  Declaration order is the
    inheritance chain -- Component's properties, then TrackGroup's, then the
    class's own -- and preserving it is what lets the grid group on it.
    """
    out = []
    if _is_object(obj):
        data = obj.property_data
        for pdef in obj.propertydefs:
            if pdef.name not in data:
                continue
            out.append((pdef.name, data[pdef.name]))
    elif isinstance(obj, dict):
        for key in sorted(obj.keys()):
            out.append((unicode(key), obj[key]))
    return out


def declaring_classes(obj):
    """Property name -> the class in the MRO that introduced it.

    pyavb flattens inherited properties into each class's `propertydefs`, so
    the chain has to be recovered by differencing the MRO.  This is the same
    information an OMF property name carries in its `OMFI:CPNT:` prefix, and
    it is what turns a flat thirty-row grid into five short readable ones.
    """
    owner = {}
    order = []
    mro = [c for c in reversed(type(obj).__mro__)
           if hasattr(c, 'propertydefs') and c.propertydefs]
    seen = set()
    for cls in mro:
        fresh = [p.name for p in cls.propertydefs if p.name not in seen]
        if not fresh:
            continue
        order.append(cls.__name__)
        for name in fresh:
            owner[name] = cls.__name__
            seen.add(name)
    return owner, order


# ------------------------------------------------------------------ session

class Session(object):
    """One open file, and the handles handed out against it.

    A handle is `o<instance_id>` for a real AVB object and `s<n>` for anything
    else.  The `s` case is not an edge case: an AVB Track is not a top-level
    chunk, so pyavb reads it inline inside its TrackGroup and it carries no
    instance ID at all.  Neither does a list, a dict, or a parameter entry.

    Synthetic handles are memoised on object identity, which matters more
    than it looks: minting a fresh one per call would mean the `tracks` list
    reached through the grid and the same list reached through the tree were
    two different handles for one object, and a link from one to the other
    would land nowhere.  The registry holds a strong reference, so the id can
    never be reused underneath us -- and holding it is also what keeps the
    value alive, since pyavb's own object cache is weak.
    """

    def __init__(self, data, name='bin.avb'):
        self.name = name
        self.size = len(data)
        self._buf = io.BytesIO(bytes(data))
        try:
            self.f = avb.open(self._buf)
        except ValueError:
            # pyavb says "not a avb file" for anything without the two-byte
            # byte-order mark and the `Domain` magic.  Say which file, and say
            # it in words the person who just dragged it in can act on.
            raise ValueError('%s is not an Avid bin: no AVB header. '
                             'Media Composer bins are .avb; an .avp project '
                             'file or an .mxf is a different format.' % name)
        self.root = self.f.content

        self._synthetic = {}        # 's12' -> the live Python value
        self._synth_by_id = {}      # id(value) -> 's12', so handles are stable
        self._next_synth = 0
        self._pinned = {}           # handle -> object, to outlive the weak cache
        self._index = None
        self._mob_handles = {}      # MobID bytes -> 'o12', built by index()

    # ------------------------------------------------------------ handles
    def handle_for(self, value):
        """A handle for a value, minting one if it does not have a natural ID.

        Objects keep a strong reference in `_pinned`: pyavb's own cache is a
        WeakValueDictionary, and a node the user can still see in the tree
        must not be collected out from under the next click.
        """
        if _is_object(value) and getattr(value, 'instance_id', None):
            h = 'o%d' % value.instance_id
            self._pinned[h] = value
            return h
        key = id(value)
        existing = self._synth_by_id.get(key)
        if existing is not None:
            return existing
        self._next_synth += 1
        h = 's%d' % self._next_synth
        self._synthetic[h] = value
        self._synth_by_id[key] = h
        return h

    def resolve(self, handle):
        if handle is None or handle == '':
            return self.root
        if handle == 'root':
            return self.root
        if handle.startswith('s'):
            return self._synthetic.get(handle)
        if handle.startswith('o'):
            pinned = self._pinned.get(handle)
            if pinned is not None:
                return pinned
            try:
                index = int(handle[1:])
            except ValueError:
                return None
            obj = self.f.read_object(index)
            if obj is not None:
                self._pinned[handle] = obj
            return obj
        return None

    # --------------------------------------------------------------- meta
    def meta(self):
        f = self.f
        return {
            'name': self.name,
            'size': self.size,
            'objects': max(0, len(f.object_positions) - 1),
            'byteOrder': 'little' if f.ictx.byte_order == 'little' else 'big',
            'creator': unicode(getattr(f, 'creator_version', '') or '').strip(),
            'lastSave': (f.last_save.strftime('%Y-%m-%d %H:%M:%S')
                         if getattr(f, 'last_save', None) else ''),
            'rootClass': _fourcc(getattr(self.root, 'class_id', None)),
            'rootHandle': self.handle_for(self.root),
            'version': MODEL_VERSION,
        }

    # -------------------------------------------------------------- index
    def index(self, progress=None):
        """Read every object once; keep a summary of each.

        This is the only whole-file pass.  It answers three questions the
        lazy tree cannot: what classes are in here and how many of each, what
        points at what, and where the mob lens should start.

        Objects are *not* retained.  Each one is summarised and dropped; the
        weak cache lets it go, and `resolve()` re-reads it from its recorded
        position if the user ever selects it.  Cost is one linear read.
        """
        if self._index is not None:
            return self._index

        f = self.f
        census = {}
        classes = {}
        labels = {}
        mobs = {}
        referrers = {}
        mob_refs = []               # (handle, MobID key) -- resolved after
        total = max(0, len(f.object_positions) - 1)

        for i in range(1, total + 1):
            if progress and (i % 2000 == 0):
                progress(i, total)
            try:
                obj = f.read_object(i)
            except Exception:
                continue
            if obj is None:
                continue

            cc = _fourcc(obj.class_id) or '????'
            census[cc] = census.get(cc, 0) + 1
            classes.setdefault(cc, _class_name(obj))

            handle = 'o%d' % i
            label = self._label_of(obj)
            if label:
                labels[handle] = label

            # References, read raw.  `property_data.values()` is the plain
            # dict view and so yields AVBObjectRef rather than resolving it,
            # which is the difference between an index pass and a full
            # materialisation of the object graph.
            for target in self._raw_refs(obj):
                referrers.setdefault('o%d' % target, []).append(handle)

            # MobID references are the other kind of edge.  A SourceClip does
            # not point at its mob by object index but by MobID, so it has to
            # wait until every mob has been seen before it can be resolved.
            own = None
            if isinstance(obj, _trackgroups.Composition):
                mobs[handle] = self._mob_summary(obj)
                own = _mob_key(obj.property_data.get('mob_id', None))
                if own:
                    self._mob_handles[own] = handle
            # Not every object has property_data: an Attributes dict is a
            # dict, and carries its entries directly.
            data = getattr(obj, 'property_data', None) or {}
            for item in dict.values(data):
                key = _mob_key(item)
                if key and key != own:
                    mob_refs.append((handle, key))

        for handle, key in mob_refs:
            target = self._mob_handles.get(key)
            if target is not None:
                referrers.setdefault(target, []).append(handle)

        roots = self._mob_roots(mobs)
        self._index = {
            'census': census,
            'classes': classes,
            'labels': labels,
            'mobs': mobs,
            'roots': roots,
            'referrers': referrers,
        }
        return self._index

    def _raw_refs(self, obj):
        """Object indexes this object points at, without dereferencing them.

        Reading `property_data` through `dict.values` rather than its own
        `.values()` is the whole trick: AVBPropertyData resolves an
        AVBObjectRef on the way out, and resolving one here would turn a
        linear index pass into a full materialisation of the object graph.
        """
        out = []
        self._collect_ref(obj, out, 0)
        return out

    def _collect_ref(self, value, out, depth):
        if depth > 4:
            return

        if isinstance(value, avb.utils.AVBObjectRef):
            if isinstance(value.index, _INTS) and value.index > 0:
                out.append(value.index)
            return

        if isinstance(value, avb.core.AVBRefList):
            # A ref list stores bare indexes; a plain list (a colour, a rect)
            # stores numbers that mean nothing of the sort.
            for item in list.__iter__(value):
                if isinstance(item, _INTS):
                    if item > 0:
                        out.append(item)
                else:
                    self._collect_ref(item, out, depth + 1)
            return

        if isinstance(value, list):
            for item in value:
                if not isinstance(item, (_INTS, float, bool)):
                    self._collect_ref(item, out, depth + 1)
            return

        data = getattr(value, 'property_data', None)
        if data is None:
            return
        # Descend into helper objects -- a BinItem, a SiftItem -- because they
        # have no ID of their own and so never get their own pass.  Stop at
        # anything with a class_id: that object is indexed in its own right,
        # and following it here would attribute its references to its parent.
        if depth and getattr(value, 'class_id', None):
            return
        for item in dict.values(data):
            self._collect_ref(item, out, depth + 1)

    # -------------------------------------------------------- mob helpers
    _MOB_KINDS = {1: 'composition', 2: 'master', 3: 'source'}

    def _label_of(self, obj):
        for attr in ('name', 'parameter_name'):
            try:
                value = getattr(obj, attr, None)
            except Exception:
                value = None
            if value:
                return unicode(value)[:200]
        return self._nick(obj)

    def _nick(self, obj):
        """A short label for an object that carries no name of its own.

        Only Tracks get one, and they earn it: six rows all reading "Track"
        under a mob is a list with the one useful column missing.  `V1`, `A3`,
        `TC1` is how the same track is labelled in the timeline the user has
        open next to this window.  Everything else keeps the Qt tool's
        behaviour and falls back to its class name.
        """
        if not isinstance(obj, _trackgroups.Track):
            return ''
        try:
            data = obj.property_data
            index = data.get('index', None)
            kind_id = data.get('media_kind_id', None)
            if kind_id is None:
                component = data.get('component', None)
                if component is not None:
                    kind_id = component.property_data.get('media_kind_id', None)
        except Exception:
            return ''
        if index is None:
            return ''
        return '%s%s' % (self._TRACK_LETTER.get(kind_id, 'T'), index)

    def _mob_summary(self, mob):
        try:
            mob_type = mob.property_data.get('mob_type_id', 0)
        except Exception:
            mob_type = 0
        kind = self._MOB_KINDS.get(mob_type, 'other')
        try:
            mob_id = mob.property_data.get('mob_id', None)
        except Exception:
            mob_id = None
        return {
            'name': self._label_of(mob),
            'kind': kind,
            'mobId': unicode(mob_id) if mob_id else '',
            'tracks': self._track_summary(mob),
        }

    def _mob_label(self, handle):
        info = (self._index or {}).get('mobs', {}).get(handle)
        return info['name'] if info else ''

    _TRACK_LETTER = {1: 'V', 2: 'A', 3: 'D', 4: 'TC', 5: 'EA', 6: 'P'}

    def _track_summary(self, mob):
        """`V1 A1-4 TC1` -- the edit-suite shorthand.

        Consecutive numbers within a kind collapse to a range, which is the
        only reason a master mob's twenty-four audio tracks fit a column.
        Track numbering restarts per media kind, exactly as Media Composer
        presents it.
        """
        try:
            tracks = mob.property_data.get('tracks', None) or []
        except Exception:
            return ''
        buckets = {}
        order = []
        for track in tracks:
            try:
                kind_id = track.property_data.get('media_kind_id', None)
                if kind_id is None:
                    component = track.property_data.get('component', None)
                    kind_id = (component.property_data.get('media_kind_id', 0)
                               if component is not None else 0)
                index = track.property_data.get('index', 0)
            except Exception:
                continue
            letter = self._TRACK_LETTER.get(kind_id, 'T')
            if letter not in buckets:
                buckets[letter] = []
                order.append(letter)
            buckets[letter].append(index)

        parts = []
        for letter in order:
            parts.append(letter + _ranges(sorted(set(buckets[letter]))))
        return ' '.join(parts)

    def mob_target(self, value, owner=None):
        """Where a MobID-valued property leads.

            ('mob', 'o12')    a mob in this bin
            ('missing', None) a real MobID naming a mob that lives elsewhere
            (None, None)      not a MobID, the zero MobID, or the owner's own

        `owner` is the handle of the object carrying the property, so that a
        Composition's own `mob_id` is not offered as a link to itself.
        """
        key = _mob_key(value)
        if key is None:
            return None, None
        self.index()
        target = self._mob_handles.get(key)
        if target is None:
            return 'missing', None
        if target == owner:
            return None, None
        return 'mob', target

    def track_target(self, clip, owner=None):
        """Where a SourceClip's `track_id` leads, given the clip itself.

            ('track', 's7', 'V1')   that track, inside the mob `mob_id` names
            ('missing', None, 'V3') the mob is here but has no such track
            (None, None, '')        no mob to look in, so nothing to say

        A `track_id` alone is only a number: V1 and A1 are both 1.  It means
        a track only together with the clip's `mob_id` and its media kind,
        which is how pyavb's own `SourceClip.track` matches it -- same label
        number, same kind.  The Track is read inline inside its mob and has no
        instance ID, so its handle is a synthetic one; it is memoised on the
        pinned mob's Track object, which makes it the same handle the mob's
        `tracks` list hands out, and the ancestor-path check sees one node.
        """
        data = getattr(clip, 'property_data', None)
        if data is None:
            return None, None, ''
        state, mob_handle = self.mob_target(data.get('mob_id', None), owner)
        if state != 'mob':
            return None, None, ''
        track_id = data.get('track_id', None)
        if not isinstance(track_id, _INTS):
            return None, None, ''
        kind_id = data.get('media_kind_id', None)
        wanted = '%s%s' % (self._TRACK_LETTER.get(kind_id, 'T'), track_id)

        mob = self.resolve(mob_handle)
        try:
            tracks = mob.property_data.get('tracks', None) or []
        except Exception:
            tracks = []
        for track in tracks:
            try:
                tdata = track.property_data
                if tdata.get('index', None) != track_id:
                    continue
                t_kind = tdata.get('media_kind_id', None)
                if t_kind is None:
                    component = tdata.get('component', None)
                    t_kind = (component.property_data.get('media_kind_id', None)
                              if component is not None else None)
            except Exception:
                continue
            if kind_id is None or t_kind == kind_id:
                return 'track', self.handle_for(track), \
                    self._nick(track) or wanted
        return 'missing', None, wanted

    def _mob_roots(self, mobs):
        roots = {'master': [], 'source': [], 'composition': [], 'other': []}
        for handle, info in mobs.items():
            roots.setdefault(info['kind'], []).append(handle)
        for key in roots:
            roots[key].sort(key=lambda h: (mobs[h]['name'].lower(), h))
        return roots

    # --------------------------------------------------------- the grid
    def node(self, handle):
        """One node, fully described, for the property grid."""
        value = self.resolve(handle)
        if value is None:
            return None

        if not _is_object(value):
            # A list or a dict selected in the raw tree still deserves a
            # grid; it just has no inheritance chain to group on.
            rows = []
            for name, item in object_properties(value) if isinstance(value, dict) \
                    else [( '[%d]' % i, v) for i, v in enumerate(value or [])]:
                rows.append(self._row(name, item, ''))
            return {
                'handle': handle,
                'cls': '',
                'py': pretty_value(value)[1],
                'label': '',
                'groups': [{'name': 'Items', 'rows': rows}] if rows else [],
            }

        owner, order = declaring_classes(value)
        defs = getattr(value, 'propertydefs_dict', None) or {}
        grouped = {}
        for name, item in object_properties(value):
            group = owner.get(name, 'Other')
            grouped.setdefault(group, []).append(
                self._row(name, item, _type_name(defs.get(name)), handle,
                          value))

        groups = [{'name': g, 'rows': grouped[g]} for g in order if g in grouped]
        for g in grouped:
            if g not in order:
                groups.append({'name': g, 'rows': grouped[g]})

        return {
            'handle': handle,
            'cls': _fourcc(value.class_id),
            'py': _class_name(value),
            'label': self._label_of(value),
            'groups': groups,
        }

    def _row(self, name, item, type_name, owner=None, owner_obj=None):
        kind, text, note = pretty_value(item)
        row = {'n': name, 'k': kind, 'v': text, 'note': note, 't': type_name}
        if kind == 'str' and len(text) < len(unicode(item)):
            # the grid draws the first 300 characters; an export wants them all
            row['full'] = unicode(item)
        if kind == 'id':
            # A MobID is a reference in everything but type: it names a mob
            # the way an object ref names a chunk.  Resolve it here, so the
            # grid can offer it as a link rather than as text to search for.
            state, target = self.mob_target(item, owner)
            if state == 'mob':
                row['ref'] = target
                row['refCls'] = 'CMPO'
                label = self._mob_label(target)
                if label:
                    row['refLabel'] = label
            elif state == 'missing':
                row['note'] = 'not in this bin'
        elif name == 'track_id' and owner_obj is not None:
            state, target, label = self.track_target(owner_obj, owner)
            if state == 'track':
                row['ref'] = target
                row['refLabel'] = label
            elif state == 'missing':
                row['note'] = 'no %s in that mob' % label
        elif kind == 'object':
            row['ref'] = self.handle_for(item)
            row['refCls'] = _fourcc(item.class_id)
            label = self._label_of(item)
            if label:
                row['refLabel'] = label
        elif kind in ('list', 'dict') and len(item):
            row['ref'] = self.handle_for(item)
        return row

    # ---------------------------------------------------------- raw tree
    def children(self, handle):
        """The raw tree's children of one node.

        This is `TreeItem.setup()` from the Qt tool, returned as data rather
        than as objects: an AVBObject or dict yields its properties, a list
        yields its items, and anything else yields nothing.
        """
        value = self.resolve(handle)
        if value is None:
            return []

        out = []
        if _is_object(value) or isinstance(value, dict):
            for name, item in object_properties(value):
                if item is None:
                    continue
                out.append(self._child(name, item, handle, value))
        elif isinstance(value, list):
            for i, item in enumerate(value):
                out.append(self._child(self._child_label(item, i), item))
        return out

    def _child_label(self, item, index):
        """The name a list item shows under its parent.

        The Qt tool's rule, with one addition: a `name`, else a
        `parameter_name`, else the derived nickname, else the class name --
        and the index in front of all of them, because eight SourceClips
        under a Sequence are otherwise eight identical rows.
        """
        if _is_object(item):
            label = self._label_of(item) or _class_name(item)
        else:
            label = pretty_value(item)[1]
        return '[%d] %s' % (index, label)

    def _child(self, name, item, owner=None, owner_obj=None):
        kind, text, note = pretty_value(item)
        child = {
            'name': name,
            'kind': kind,
            'value': text,
            'note': note,
            'has': _expandable(item),
        }
        if kind == 'str' and len(text) < len(unicode(item)):
            child['full'] = unicode(item)
        if kind == 'id':
            # Follow a MobID to the mob it names, so a SourceClip opens onto
            # the master or source mob it cuts from without a search.  The
            # child keeps kind 'id' -- the row is still the property, with its
            # UMID as the value -- and gains the target's handle, which is all
            # either lens needs to expand it.  `follow` says which case it is.
            state, target = self.mob_target(item, owner)
            if state == 'mob':
                child['follow'] = 'mob'
                child['handle'] = target
                child['cls'] = 'CMPO'
                child['has'] = True
                label = self._mob_label(target)
                if label:
                    child['label'] = label
                    child['note'] = '\u2192 ' + label
            elif state == 'missing':
                child['follow'] = 'missing'
                child['note'] = 'not in this bin'
        elif name == 'track_id' and owner_obj is not None:
            # The companion to `mob_id`: not the whole mob, the one track in
            # it this clip cuts from.
            state, target, label = self.track_target(owner_obj, owner)
            if state == 'track':
                child['follow'] = 'track'
                child['handle'] = target
                child['has'] = True
                child['label'] = label
                mob = self._mob_label(self._mob_handles.get(
                    _mob_key(owner_obj.property_data.get('mob_id', None))))
                child['note'] = '\u2192 ' + label + (' in ' + mob if mob else '')
            elif state == 'missing':
                child['follow'] = 'missing'
                child['note'] = 'no %s in that mob' % label
        elif _is_object(item):
            child['cls'] = _fourcc(item.class_id)
            child['handle'] = self.handle_for(item)
            label = self._label_of(item)
            if label:
                child['label'] = label
        elif child['has']:
            child['handle'] = self.handle_for(item)
        return child

    # ---------------------------------------------------------- mob lens
    def mob_children(self, handle):
        """The mob lens's children: tracks, then what each track resolves to.

        Deliberately the same row shape as `children()`, so the table does not
        need to know which lens it is drawing.
        """
        return self.children(handle)

    # ---------------------------------------------------------- searching
    def search(self, query):
        """Handles whose label, class, or MobID matches.

        Runs over the index summaries rather than the objects, so it costs a
        scan of a few thousand short strings and needs no maintained index.
        """
        q = (query or '').strip().lower()
        if not q:
            return None
        idx = self.index()
        hits = []
        for handle, label in idx['labels'].items():
            if q in label.lower():
                hits.append(handle)
        for handle, info in idx['mobs'].items():
            if handle in hits:
                continue
            if q in info['mobId'].lower() or q == info['kind']:
                hits.append(handle)
        # a bare class 4CC selects every object of that class
        if len(q) <= 4:
            upper = q.upper()
            for handle in self._handles_of_class(upper):
                if handle not in hits:
                    hits.append(handle)
        return hits

    def _handles_of_class(self, fourcc):
        out = []
        f = self.f
        target = fourcc.encode('ascii', 'ignore')
        if len(target) != 4:
            return out
        for i, chunk in enumerate(f.chunks()):
            if chunk.class_id == target:
                out.append('o%d' % i)
        return out

    # ----------------------------------------------------------- dumping
    def _xml_open(self, extra=''):
        m = self.meta()
        return ('<?xml version="1.0" encoding="UTF-8"?>\n<avb%s>\n' % (
            _attr('file', m['name']) + _attr('size', m['size'])
            + _attr('byteOrder', m['byteOrder'])
            + (_attr('creator', m['creator']) if m['creator'] else '')
            + (_attr('lastSave', m['lastSave']) if m['lastSave'] else '')
            + _attr('pyavb', _pyavb_version())
            + _attr('generator', 'AVBrowse model %d' % MODEL_VERSION)
            + extra))

    def _xml_value(self, dumper, value, depth):
        if _is_object(value) or getattr(value, 'class_id', None):
            dumper.obj(value, depth, frozenset())
        elif isinstance(value, dict):
            dumper.value(value, depth, frozenset(), 'dict')
        else:
            dumper.value(value, depth, frozenset(), 'list')

    def dump_xml(self, handle=None):
        """The subtree under `handle` -- the whole bin by default -- as XML.

        dump.py's walk: see `_XMLDumper`.  The index pass runs first if it has
        not already, because MobID annotations need the mob table.
        """
        value = self.resolve(handle)
        if value is None:
            return ''
        self.index()
        out = io.StringIO()
        root = handle in (None, '', 'root') or value is self.root
        out.write(self._xml_open('' if root else _attr('subtree', handle)))
        self._xml_value(_XMLDumper(self, out), value, 1)
        out.write('</avb>\n')
        return out.getvalue()

    def dump_xml_sections(self, sections_json):
        """Several objects in one document, grouped the way the page groups a
        selection: `[{"kind": "master", "label": "Master mobs",
        "handles": ["o12", ...]}, ...]`, as JSON.

            <avb ... selection="3">
              <section kind="master" label="Master mobs" count="2">
                <Composition .../>

        Each object is dumped whole, exactly as `dump_xml` would dump it on
        its own; the section element is the only thing added.
        """
        import json
        sections = json.loads(sections_json)
        self.index()
        total = sum(len(s.get('handles', [])) for s in sections)
        out = io.StringIO()
        out.write(self._xml_open(_attr('selection', total)))
        dumper = _XMLDumper(self, out)
        for section in sections:
            handles = section.get('handles', [])
            out.write('  <section%s%s%s>\n' % (
                _attr('kind', section.get('kind', '')),
                _attr('label', section.get('label', '')),
                _attr('count', len(handles))))
            for handle in handles:
                try:
                    value = self.resolve(handle)
                except Exception:
                    value = None
                if value is None:
                    out.write('    <missing%s/>\n' % _attr('handle', handle))
                    continue
                self._xml_value(dumper, value, 2)
            out.write('  </section>\n')
        out.write('</avb>\n')
        return out.getvalue()

    def dump_text(self, handle=None):
        """The subtree under `handle` in pyavb's dump.py format, exactly."""
        value = self.resolve(handle)
        if value is None:
            return ''
        out = io.StringIO()
        _dump_text(value, out)
        return out.getvalue()

    def close(self):
        try:
            self.f.close()
        except Exception:
            pass
        self._synthetic = {}
        self._synth_by_id = {}
        self._pinned = {}


def _pyavb_version():
    try:
        return unicode(avb.__version__)
    except Exception:
        return ''


def _mob_key(value):
    """A MobID as a hashable key, or None for anything else.

    The all-zero MobID is None too: it is what a SourceClip carries at the
    end of a derivation chain -- "no further source" -- and it points at
    nothing, which is different from pointing at a mob this bin lacks.
    """
    if not isinstance(value, _mobid.MobID):
        return None
    data = bytes(value.bytes_le)
    if not any(bytearray(data)):
        return None
    return data


def _ranges(numbers):
    """[1,2,3,5] -> '1-3,5'."""
    if not numbers:
        return ''
    out = []
    start = prev = numbers[0]
    for n in numbers[1:]:
        if n == prev + 1:
            prev = n
            continue
        out.append(_span(start, prev))
        start = prev = n
    out.append(_span(start, prev))
    return ','.join(out)


def _span(a, b):
    return unicode(a) if a == b else '%s-%s' % (a, b)


# ------------------------------------------------------------------ dumping
#
# Two whole-subtree dumps, both built on the walk in pyavb's own
# `examples/dump.py`: every property an object actually carries, in
# declaration order; a dict's keys sorted; a list's items in order; a None
# skipped.  Nothing is lazy and nothing is truncated -- these are exports, and
# an export that stops at 300 characters is a screenshot.
#
# `dump_text` is dump.py's output, byte for byte, so a diff against the
# command-line tool is a meaningful diff.  `dump_xml` is the same walk with
# the structure dump.py's indentation cannot carry: in dump.py a list of dicts
# prints as one undivided run of keys -- a bin view's twenty columns read as
# eighty lines with nothing between one column and the next -- and an
# element per item is what puts the boundaries back.

# bytes per line of a wrapped hex body
_HEX_LINE = 64


def _xml_name_ok(name):
    """Can this string be an element name as it stands?

    Every pyavb property name is (they are Python identifiers), but the test
    is cheap and the fallback -- `<property name="...">` -- is what keeps an
    odd one from producing a file no parser will open.
    """
    if not name or name.lower().startswith('xml'):
        return False
    first = name[0]
    if not (first.isalpha() or first == '_'):
        return False
    for ch in name:
        if not (ch.isalnum() or ch in '_-.'):
            return False
    return all(ord(ch) < 128 for ch in name)


def _xml_legal(ch):
    o = ord(ch)
    return (o in (0x9, 0xA, 0xD) or 0x20 <= o <= 0xD7FF
            or 0xE000 <= o <= 0xFFFD or 0x10000 <= o <= 0x10FFFF)


def _xml_text(text):
    """(escaped text, needed-backslash-escaping).

    XML 1.0 cannot carry most control characters at all -- not even as a
    character reference -- and Avid strings do contain them.  Rather than
    drop them, a string that has any is written with those characters as
    `\\xNN` (and its real backslashes doubled), and the element says so with
    `escaped="backslash"`, which makes the encoding reversible.
    """
    text = unicode(text)
    if all(_xml_legal(ch) for ch in text):
        return _xml_escape(text), False
    out = []
    for ch in text:
        if ch == '\\':
            out.append('\\\\')
        elif _xml_legal(ch):
            out.append(ch)
        else:
            o = ord(ch)
            out.append('\\x%02x' % o if o < 0x100 else '\\u%04x' % o)
    return _xml_escape(''.join(out)), True


def _xml_escape(text):
    return (text.replace('&', '&amp;').replace('<', '&lt;')
            .replace('>', '&gt;').replace('"', '&quot;'))


def _attr(name, value):
    text, _ = _xml_text(value)
    return ' %s="%s"' % (name, text)


def export_scalar(value):
    """(type, text) for a leaf value, at full fidelity.

    The grid's `pretty_value` is for reading; this is for keeping.  Blobs are
    written out in full as hex, strings are not capped, dates are ISO 8601.
    """
    if isinstance(value, (bytes, bytearray)):
        return 'bytes', ''.join('%02x' % b for b in bytearray(value))
    if isinstance(value, bool):
        return 'bool', 'true' if value else 'false'
    if isinstance(value, _INTS):
        return 'int', unicode(value)
    if isinstance(value, float):
        return 'float', repr(value)
    if isinstance(value, _mobid.MobID):
        return 'MobID', unicode(value)
    if isinstance(value, datetime.datetime):
        return 'datetime', value.isoformat()
    if isinstance(value, datetime.date):
        return 'date', value.isoformat()
    return _class_name(value) if not isinstance(value, unicode) else 'str', \
        unicode(value)


class _XMLDumper(object):
    """dump.py's walk, written as XML.

        <Composition fourcc="CMPO" id="o28" mobKind="master">
          <name type="str">AR1001_SC12_v04</name>
          <mob_id type="MobID" mob="o28">urn:smpte:umid:...</mob_id>
          <tracks count="2">
            <Track label="V1">
              <index type="int">1</index>
              ...

    An object is an element named for its pyavb class, with its 4CC, its
    AVBrowse handle where it has an instance ID, and the derived labels the
    tree shows (`V1`, the mob kind).  A property is an element named for the
    property.  A dict entry is `<entry key="...">`, because dict keys are user
    strings -- bin column names, attribute names -- and need not be names.

    MobID and track references are annotated, not followed: `mob="o12"
    mobName="..."` on the property says where it leads, and following it
    would print the same master mob once per clip that cuts from it.  That
    is the screen's job (the mob lens and the tree exports); this one says
    what the file says.
    """

    def __init__(self, session, out, indent='  '):
        self.s = session
        self.out = out
        self.indent = indent
        self.objects = 0

    def w(self, depth, text):
        self.out.write(self.indent * depth)
        self.out.write(text)
        self.out.write('\n')

    # an object -------------------------------------------------------
    def obj(self, value, depth, path, tag=None, extra=''):
        name = tag or _class_name(value)
        attrs = extra
        if tag:
            attrs += _attr('class', _class_name(value))
        cc = _fourcc(getattr(value, 'class_id', None))
        if cc:
            attrs += _attr('fourcc', cc)
        iid = getattr(value, 'instance_id', None)
        if iid:
            attrs += _attr('id', 'o%d' % iid)
        nick = self.s._nick(value) if _is_object(value) else ''
        if nick:
            attrs += _attr('label', nick)
        if isinstance(value, _trackgroups.Composition) and iid:
            info = (self.s._index or {}).get('mobs', {}).get('o%d' % iid)
            if info:
                attrs += _attr('mobKind', info['kind'])

        key = id(value)
        if key in path:
            # an object on its own ancestor path: the tree marks it with an
            # arrow and refuses it children, and so does this
            self.w(depth, '<%s%s cycle="true"/>' % (name, attrs))
            return
        self.objects += 1
        props = object_properties(value) if _is_object(value) else None
        if props is None:                       # a dict that is also a chunk
            props = [(k, value[k]) for k in sorted(value.keys())]
            entries = True
        else:
            entries = False
        props = [(k, v) for k, v in props if v is not None]
        if not props:
            self.w(depth, '<%s%s/>' % (name, attrs))
            return
        self.w(depth, '<%s%s>' % (name, attrs))
        path = path | {key}
        for k, v in props:
            if entries:
                self.value(v, depth + 1, path, 'entry', _attr('key', k))
            else:
                self.prop(value, k, v, depth + 1, path)
        self.w(depth, '</%s>' % name)

    def prop(self, owner, key, value, depth, path):
        if _xml_name_ok(key):
            tag, extra = key, ''
        else:
            tag, extra = 'property', _attr('name', key)
        if isinstance(value, _mobid.MobID):
            iid = getattr(owner, 'instance_id', None)
            state, target = self.s.mob_target(
                value, 'o%d' % iid if iid else None)
            if state == 'mob':
                extra += _attr('mob', target)
                label = self.s._mob_label(target)
                if label:
                    extra += _attr('mobName', label)
            elif state == 'missing':
                extra += _attr('mob', 'not in this bin')
        elif key == 'track_id' and _is_object(owner):
            iid = getattr(owner, 'instance_id', None)
            state, _, label = self.s.track_target(
                owner, 'o%d' % iid if iid else None)
            if state == 'track':
                extra += _attr('track', label)
            elif state == 'missing':
                extra += _attr('track', 'no %s in that mob' % label)
        self.value(value, depth, path, tag, extra)

    # any value under a given tag --------------------------------------
    def value(self, value, depth, path, tag, extra=''):
        if _is_object(value) or (isinstance(value, dict)
                                 and getattr(value, 'class_id', None)):
            # A property holding an object: the property element wraps the
            # object element, so `//SourceClip` and `//component` both work.
            self.w(depth, '<%s%s>' % (tag, extra))
            self.obj(value, depth + 1, path)
            self.w(depth, '</%s>' % tag)
            return
        if isinstance(value, dict):
            items = [(k, value[k]) for k in sorted(value.keys(), key=unicode)]
            items = [(k, v) for k, v in items if v is not None]
            if not items:
                self.w(depth, '<%s%s count="0"/>' % (tag, extra))
                return
            self.w(depth, '<%s%s count="%d">' % (tag, extra, len(value)))
            for k, v in items:
                self.value(v, depth + 1, path, 'entry', _attr('key', k))
            self.w(depth, '</%s>' % tag)
            return
        if isinstance(value, list):
            if not value:
                self.w(depth, '<%s%s count="0"/>' % (tag, extra))
                return
            self.w(depth, '<%s%s count="%d">' % (tag, extra, len(value)))
            for item in value:
                if _is_object(item):
                    self.obj(item, depth + 1, path)
                elif item is None:
                    self.w(depth + 1, '<item/>')
                else:
                    self.value(item, depth + 1, path, 'item')
            self.w(depth, '</%s>' % tag)
            return
        kind, text = export_scalar(value)
        body, escaped = _xml_text(text)
        attrs = extra + _attr('type', kind)
        if kind == 'bytes':
            attrs += _attr('size', len(value)) + _attr('encoding', 'hex')
            raw = bytearray(value)
            if 0 < len(raw) <= 16 and all(0x20 <= b < 0x7f for b in raw):
                # a 4CC stored as bytes -- `compress_method` and friends --
                # reads as what it is, not only as eight hex digits
                attrs += _attr('ascii', raw.decode('ascii'))
            if len(raw) > _HEX_LINE:
                # A thumbnail's pict_data is hundreds of kilobytes; on one
                # line it is a file no editor wants to open.  Whitespace
                # inside a hex body is insignificant.
                self.w(depth, '<%s%s>' % (tag, attrs))
                step = _HEX_LINE * 2
                for i in range(0, len(text), step):
                    self.w(depth + 1, text[i:i + step])
                self.w(depth, '</%s>' % tag)
                return
        if escaped:
            attrs += _attr('escaped', 'backslash')
        self.w(depth, '<%s%s>%s</%s>' % (tag, attrs, body, tag))


def _dump_text(obj, out, space=''):
    """pyavb's examples/dump.py, writing to `out` instead of stdout.

    Kept line for line -- including `print(space, x)` putting a space between
    the indent and the value -- so that its output diffs clean against the
    script's.
    """
    def p(*parts):
        out.write(' '.join(unicode(x) for x in parts))
        out.write('\n')

    keys = []
    data = None
    if _is_object(obj):
        p(space, unicode(obj))
        space += '  '
        data = obj.property_data
        for pdef in obj.propertydefs:
            if pdef.name not in obj.property_data:
                continue
            keys.append(pdef.name)
    elif isinstance(obj, dict):
        keys = sorted(obj.keys())
        data = obj
    else:
        p(space, obj)
        return

    for key in keys:
        value = data[key]
        if isinstance(value, (avb.core.AVBObject, dict)):
            p('%s%s:' % (space, key))
            _dump_text(value, out, space + ' ')
        elif isinstance(value, list):
            p('%s%s:' % (space, key))
            for item in value:
                _dump_text(item, out, space + ' ')
        elif value is not None:
            if isinstance(value, bytearray):
                value = 'bytearray(%d)' % len(value)
            p('%s%s:' % (space, key), value)
