package pcd

import (
	"fmt"

	pkgbytes "github.com/linuxboot/fiano/pkg/bytes"
	"github.com/linuxboot/fiano/pkg/guid"
	"github.com/linuxboot/fiano/pkg/uefi"
)

func init() {
	addFirmwareParser(ParseFirmwareDummy)
}

// ParseFirmwareDummy is a variant of ParseFirmware for dummy firmware,
// generated by ../../testdata/firmware/scripts/generate_fake_intel_firmware.sh
func ParseFirmwareDummy(
	firmwareImage FirmwareImage,
) (ParsedFirmware, error) {
	firmwareVersionFileGUID := *guid.MustParse("658ABE96-545D-4797-BDCC-B9BE16AAD5EE")
	nodes, err := firmwareImage.GetByGUID(firmwareVersionFileGUID)
	if err != nil {
		return nil, fmt.Errorf("unable to parse the firmware: %w", err)
	}
	if len(nodes) == 0 {
		return nil, nil
	}
	if len(nodes) > 1 {
		return nil, &ErrTooDummyFirmwareVersionFiles{}
	}
	node := nodes[0]
	file, ok := node.Firmware.(*uefi.File)
	if !ok {
		return nil, &ErrDummyFirmwareVersionFileWrongType{}
	}
	return &ParsedFirmwareGeneric{
		FirmwareImage: firmwareImage,
		FirmwareVendorVersionCodeRanges: pkgbytes.Ranges{{
			Offset: node.Offset,
			Length: uint64(len(node.Buf())),
		}},
		FirmwareVendorVersionRanges: pkgbytes.Ranges{{
			Offset: node.Offset + file.DataOffset,
			Length: uint64(len(node.Buf())) - file.DataOffset,
		}},
		FirmwareVendorVersionFFSGUID: firmwareVersionFileGUID,
	}, nil
}
