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

// TrackExtendsBox Track Extends Box struct
//
// 8.8.3 Track Extends Box
//
// This sets up default values used by the movie fragments. By setting defaults in this way, space and
// complexity can be saved in each Track Fragment Box.
type TrackExtendsBox struct {
	*FullBox
	// identifies the track; this shall be the track ID of a track in the Movie Box
	TrackID                       uint32
	DefaultSampleDescriptionIndex uint32
	DefaultSampleDuration         uint32
	DefaultSampleSize             uint32
	DefaultSampleFlags            uint32
}

const BoxTypeTrackExtends = "trex"

func init() {
	BoxDefinitions = append(BoxDefinitions, BoxDefinition{
		Type:        BoxTypeTrackExtends,
		ParentTypes: []string{BoxTypeMovieExtends},
		Parser:      ParseTrackExtendsBox,
	})
}

// ParseTrackExtendsBox creates a new track extends box struct based on bytes
func ParseTrackExtendsBox(parser *Parser, filePosition uint64, headerSize uint32, content []byte) (any, error) {
	box := &TrackExtendsBox{
		FullBox: newFullBox(&Box{filePosition, headerSize}, content[0:4]),
	}

	box.TrackID = binary.BigEndian.Uint32(content[4:8])
	box.DefaultSampleDescriptionIndex = binary.BigEndian.Uint32(content[8:12])
	box.DefaultSampleDuration = binary.BigEndian.Uint32(content[12:16])
	box.DefaultSampleSize = binary.BigEndian.Uint32(content[16:20])
	box.DefaultSampleFlags = binary.BigEndian.Uint32(content[20:24])

	return box, nil
}
