// 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 (
	"os"
	"testing"
)

func TestMain(m *testing.M) {
	// enable debug log
	logger = verboseLogger

	// run test
	code := m.Run()
	os.Exit(code)
}

func TestParser(t *testing.T) {
	parser, err := testFile(t, "test/fmp4.mp4", false)
	if err != nil {
		t.Error(err)
	}

	// check box count
	if len(parser.Content) != 10 {
		t.Error("invalid amount of boxes", len(parser.Content))
	}

	// validate file type data
	validateFileType(t, parser)

	// TODO: validate movie fragment header data
}

func TestParserFragmentedMP4Init(t *testing.T) {
	_, err := testFile(t, "test/fmp4_init.mp4", true)
	if err != nil {
		t.Error(err)
	}
}

func validateFileType(t *testing.T, parser *Parser) {
	// get first file type box
	fileTypeBox := parser.Content[0].(*FileTypeBox)

	// check major brand
	if fileTypeBox.MajorBrand != "mp42" {
		t.Error("invalid major brand", fileTypeBox.MajorBrand)
	}

	// check minor brand
	if fileTypeBox.MinorBrand != 0x00000001 {
		t.Error("invalid minor brand", fileTypeBox.MinorBrand)
	}

	// TODO: check
}

func TestParserInvalidSampleCount(t *testing.T) {
	if _, err := testFile(t, "test/fmp4-incorrect-sample-count.mp4", false); err == nil {
		t.Error("missing error of invalid sample count of track fragment run box")
	}
}

func testFile(t *testing.T, filePath string, allowIgnore bool) (*Parser, error) {
	// open test file
	file, err := os.Open(filePath)
	if err != nil {
		t.Error(err)
	}
	defer file.Close()

	// create new parser
	parser := NewParser(file)
	parser.IgnoreUnknownBoxes = allowIgnore
	err = parser.Parse()
	return parser, err
}
