// SPDX-License-Identifier: Unlicense OR BSD-3-Clause

package opentype

import (
	
	
	
)

type woffEntry struct {
	Tag          Tag
	Offset       uint32
	CompLength   uint32
	OrigLength   uint32
	OrigChecksum uint32
}

const (
	woffHeaderSize = 44 // for the full header, but we only read Flavor and NumTables
	woffEntrySize  = 20
)

func readWOFFHeader( io.Reader) ( Tag,  uint16,  error) {
	var  [woffHeaderSize]byte
	if ,  := io.ReadFull(, [:]);  != nil {
		return 0, 0, 
	}

	return NewTag([4], [5], [6], [7]), binary.BigEndian.Uint16([12:14]), nil
}

func readWOFFEntry( io.Reader) (woffEntry, error) {
	var (
		   [woffEntrySize]byte
		 woffEntry
	)
	if ,  := io.ReadFull(, [:]);  != nil {
		return , 
	}
	.Tag = NewTag([0], [1], [2], [3])
	.Offset = binary.BigEndian.Uint32([4:8])
	.CompLength = binary.BigEndian.Uint32([8:12])
	.OrigLength = binary.BigEndian.Uint32([12:16])
	.OrigChecksum = binary.BigEndian.Uint32([16:20])
	return , nil
}

// `offset` is the beginning of the ressource in the file (non zero for collections)
// `relativeOffset` is true when the table offset are expresed relatively ot the ressource
// (that is, `offset`) rather than to the file
func parseWOFF( Resource,  uint32,  bool) (*Loader, error) {
	,  := .Seek(int64(), io.SeekStart)
	if  != nil {
		return nil, 
	}

	, ,  := readWOFFHeader()
	if  != nil {
		return nil, 
	}

	 := &Loader{
		file:   ,
		tables: make(map[Tag]tableSection, ),
		Type:   ,
	}
	for  := 0;  < int(); ++ {
		,  := readWOFFEntry()
		if  != nil {
			return nil, 
		}

		if ,  := .tables[.Tag];  {
			// ignore duplicate tables – the first one wins
			continue
		}

		 := tableSection{
			offset:  .Offset,
			length:  .CompLength,
			zLength: .OrigLength,
		}
		// adapt the relative offsets
		if  {
			.offset += 
			if .offset <  { // check for overflow
				return nil, errors.New("unsupported table offset or length")
			}
		}

		.tables[.Tag] = 
	}

	return , nil
}