package jpeg

import (
	"bytes"
	"testing"

	"github.com/stretchr/testify/require"
)

var casesDefineQuantizationTable = []struct {
	name string
	enc  []byte
	dec  DefineQuantizationTable
}{
	{
		"base",
		[]byte{
			0xff, 0xdb, 0x0, 0x84, 0x4, 0x1, 0x2, 0x3,
			0x4, 0x1, 0x2, 0x3, 0x4, 0x1, 0x2, 0x3,
			0x4, 0x1, 0x2, 0x3, 0x4, 0x1, 0x2, 0x3,
			0x4, 0x1, 0x2, 0x3, 0x4, 0x1, 0x2, 0x3,
			0x4, 0x1, 0x2, 0x3, 0x4, 0x1, 0x2, 0x3,
			0x4, 0x1, 0x2, 0x3, 0x4, 0x1, 0x2, 0x3,
			0x4, 0x1, 0x2, 0x3, 0x4, 0x1, 0x2, 0x3,
			0x4, 0x1, 0x2, 0x3, 0x4, 0x1, 0x2, 0x3,
			0x4, 0x1, 0x2, 0x3, 0x4, 0x5, 0x5, 0x6,
			0x7, 0x8, 0x5, 0x6, 0x7, 0x8, 0x5, 0x6,
			0x7, 0x8, 0x5, 0x6, 0x7, 0x8, 0x5, 0x6,
			0x7, 0x8, 0x5, 0x6, 0x7, 0x8, 0x5, 0x6,
			0x7, 0x8, 0x5, 0x6, 0x7, 0x8, 0x5, 0x6,
			0x7, 0x8, 0x5, 0x6, 0x7, 0x8, 0x5, 0x6,
			0x7, 0x8, 0x5, 0x6, 0x7, 0x8, 0x5, 0x6,
			0x7, 0x8, 0x5, 0x6, 0x7, 0x8, 0x5, 0x6,
			0x7, 0x8, 0x5, 0x6, 0x7, 0x8,
		},
		DefineQuantizationTable{
			Tables: []QuantizationTable{
				{
					ID:   4,
					Data: bytes.Repeat([]byte{0x01, 0x02, 0x03, 0x04}, 64/4),
				},
				{
					ID:   5,
					Data: bytes.Repeat([]byte{0x05, 0x06, 0x07, 0x08}, 64/4),
				},
			},
		},
	},
}

func TestDefineQuantizationTableUnmarshal(t *testing.T) {
	for _, ca := range casesDefineQuantizationTable {
		t.Run(ca.name, func(t *testing.T) {
			var h DefineQuantizationTable
			err := h.Unmarshal(ca.enc[4:])
			require.NoError(t, err)
			require.Equal(t, ca.dec, h)
		})
	}
}

func TestDefineQuantizationTableMarshal(t *testing.T) {
	for _, ca := range casesDefineQuantizationTable {
		t.Run(ca.name, func(t *testing.T) {
			byts := ca.dec.Marshal(nil)
			require.Equal(t, ca.enc, byts)
		})
	}
}

func FuzzDefineQuantizationTableUnmarshal(f *testing.F) {
	for _, ca := range casesDefineQuantizationTable {
		f.Add(ca.enc)
	}

	f.Fuzz(func(_ *testing.T, b []byte) {
		var h DefineQuantizationTable
		h.Unmarshal(b) //nolint:errcheck
	})
}
