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

const (
	boxSizeLength uint32 = 4
	boxTypeLength uint32 = 4

	boxTypeParentFile = "__file"
)

// Box is an abstract box struct
type Box struct {
	FilePosition uint64
	HeaderSize   uint32
}

// FullBox is an abstract box type extending base box
type FullBox struct {
	*Box
	Version    uint8
	Flag       []byte
	flagUInt32 uint32
}

// newFullBox parses based on 4 bytes data the version number (first byte) and the flags (bytes 2 - 4)
func newFullBox(box *Box, data []byte) *FullBox {
	fullBox := &FullBox{Box: box, Version: data[0], Flag: data[1:4]}

	// build uint32 for flags (used for easier matching)
	flag4Bytes := append(make([]byte, 1), fullBox.Flag...)
	fullBox.flagUInt32 = binary.BigEndian.Uint32(flag4Bytes)

	// extend header size
	fullBox.HeaderSize = fullBox.HeaderSize + 4

	return fullBox
}

type BoxDefinition struct {
	Type        string
	ParentTypes []string
	Parser      BoxDefinitionParser
}

type BoxDefinitionParser func(parser *Parser, filePosition uint64, headerSize uint32, content []byte) (any, error)

var BoxDefinitions []BoxDefinition
