// 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"
)

// MovieFragmentHeaderBox Movie Fragment Header Box struct
//
// 8.8.5 Movie Fragment Header Box
// Box Type: ‘mfhd’
// Container: Movie Fragment Box ('moof')
// Mandatory: Yes
// Quantity: Exactly one
//
// The movie fragment header contains a sequence number, as a safety check. The sequence number
// usually starts at 1 and increases for each movie fragment in the file, in the order in which they occur.
// This allows readers to verify integrity of the sequence in environments where undesired re‐ordering
// might occur.
type MovieFragmentHeaderBox struct {
	*FullBox
	// a number associated with this fragment
	SequenceNumber uint32
}

// BoxTypeMovieFragmentHeader Movie Fragment Header Box
const BoxTypeMovieFragmentHeader = "mfhd"

func init() {
	BoxDefinitions = append(BoxDefinitions, BoxDefinition{
		Type:        BoxTypeMovieFragmentHeader,
		ParentTypes: []string{BoxTypeMovieFragment},
		Parser:      ParseMovieFragmentHeaderBox,
	})
}

// ParseMovieFragmentHeaderBox creates a new Movie Fragment Header Box struct
func ParseMovieFragmentHeaderBox(parser *Parser, filePosition uint64, headerSize uint32, content []byte) (any, error) {
	box := &MovieFragmentHeaderBox{
		FullBox: newFullBox(&Box{filePosition, headerSize}, content[0:4]),
	}

	// parse sequence number
	box.SequenceNumber = binary.BigEndian.Uint32(content[4:8])

	return box, nil
}
