package main

import (
	"bytes"
	"encoding/binary"
	"image/png"
	"testing"
)

func TestTrayIconIsMultiSizeICO(t *testing.T) {
	ico := trayIcon
	if len(ico) < 6 {
		t.Fatalf("icon is too short: %d bytes", len(ico))
	}
	if got := binary.LittleEndian.Uint16(ico[0:2]); got != 0 {
		t.Fatalf("reserved field = %d, want 0", got)
	}
	if got := binary.LittleEndian.Uint16(ico[2:4]); got != 1 {
		t.Fatalf("icon type = %d, want 1", got)
	}
	count := int(binary.LittleEndian.Uint16(ico[4:6]))
	if count < 3 {
		t.Fatalf("entry count = %d, want at least 3", count)
	}

	seen := map[int]bool{}
	for i := 0; i < count; i++ {
		entry := 6 + i*16
		size := int(ico[entry])
		if size == 0 {
			size = 256
		}
		seen[size] = true
		dataSize := int(binary.LittleEndian.Uint32(ico[entry+8 : entry+12]))
		dataOffset := int(binary.LittleEndian.Uint32(ico[entry+12 : entry+16]))
		if dataOffset+dataSize > len(ico) {
			t.Fatalf("entry %d data range %d..%d exceeds icon length %d", i, dataOffset, dataOffset+dataSize, len(ico))
		}
		img, err := png.Decode(bytes.NewReader(ico[dataOffset : dataOffset+dataSize]))
		if err != nil {
			t.Fatalf("entry %d PNG decode failed: %v", i, err)
		}
		if got := img.Bounds().Dx(); got != int(size) {
			t.Fatalf("entry %d decoded width = %d, want %d", i, got, size)
		}
		if got := img.Bounds().Dy(); got != int(size) {
			t.Fatalf("entry %d decoded height = %d, want %d", i, got, size)
		}
	}

	for _, size := range []int{16, 32, 48, 256} {
		if !seen[size] {
			t.Fatalf("icon is missing %dx%d entry", size, size)
		}
	}
}
