// Copyright 2024 Martin Riedl
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package gomp4

import (
	"encoding/binary"
)

// HandlerReferenceBox handler reference box struct
//
// 8.4.3 Handler Reference Box
//
// Box Type: ‘hdlr’
// Container: Media Box (‘mdia’) or Meta Box (‘meta’)
// Mandatory: Yes
// Quantity: Exactly one
//
// This box within a Media Box declares media type of the track, and thus the process by which the mediadata
// in the track is presented. For example, a format for which the decoder delivers video would be
// stored in a video track, identified by being handled by a video handler. The documentation of the
// storage of a media format identifies the media type which that format uses.
//
// This box when present within a Meta Box, declares the structure or format of the 'meta' box contents.
// There is a general handler for metadata streams of any type; the specific format is identified by the
// sample entry, as for video or audio, for example.
type HandlerReferenceBox struct {
	*FullBox

	// – when present in a media box, contains a value as defined in clause 12, or a value from a derived
	// specification, or registration.
	// - when present in a meta box, contains an appropriate value to indicate the format of the meta
	// box contents. The value ‘null’ can be used in the primary meta box to indicate that it is
	// merely being used to hold resources.
	HandlerType uint32
	// is a null‐terminated string in UTF‐8 characters which gives a human‐readable name for the
	// track type (for debugging and inspection purposes).
	Name string
}

// BoxTypeHandlerReference Handler Reference Box
const BoxTypeHandlerReference = "hdlr"

func init() {
	BoxDefinitions = append(BoxDefinitions, BoxDefinition{
		Type:        BoxTypeHandlerReference,
		ParentTypes: []string{BoxTypeMedia}, // TODO: add box type `meta` (Meta Box)
		Parser:      ParseHandlerReferenceBox,
	})
}

func ParseHandlerReferenceBox(parser *Parser, filePosition uint64, headerSize uint32, content []byte) (any, error) {
	box := &HandlerReferenceBox{
		FullBox: newFullBox(&Box{filePosition, headerSize}, content[0:4]),
	}

	// box content + 32bit pre-defined
	position := 4 + 4

	// parse handler type
	box.HandlerType = binary.BigEndian.Uint32(content[position : position+4])
	position += 4

	// 3x32bit reserved
	position += 3 * 4

	// parse name
	box.Name, _ = ParseStringNullTerminated(content[position:])

	return box, nil
}
