package nori

import (
	"encoding/binary"
	"fmt"
	"io"
)

type GawiSection struct {
	Version      uint32
	Bpp          uint32
	IsCompressed bool
	Params       [4]uint32
	BmpCount     uint32
	Size         uint32

	HasPalette bool
	Palette    *PaletteSection
	Images     []*Image

	lastSignature [4]byte
}

func (g *GawiSection) Decode(rd io.Reader) error {
	if _, err := io.ReadFull(rd, g.lastSignature[:]); err != nil {
		return err
	}
	if sig, target := string(g.lastSignature[:]), "GAWI"; sig != target {
		return fmt.Errorf("bad sig: want %s, got %s", target, sig)
	}
	if err := binary.Read(rd, end, &g.Version); err != nil {
		return err
	}
	if g.Version != 300 {
		return fmt.Errorf("bad ver: want 300, got %d", g.Version)
	}
	if err := binary.Read(rd, end, &g.Bpp); err != nil {
		return err
	}
	good := false
	for _, v := range [3]uint32{8, 16, 24} {
		if g.Bpp == v {
			good = true
		}
	}
	if !good {
		return fmt.Errorf("bad bpp: %d", g.Bpp)
	}
	var container uint32
	if err := binary.Read(rd, end, &container); err != nil {
		return err
	}
	g.IsCompressed = (container == 1)
	if err := binary.Read(rd, end, &container); err != nil {
		return err
	}
	g.HasPalette = (container > 0)

	if err := binary.Read(rd, end, g.Params[:]); err != nil {
		return err
	}
	if err := binary.Read(rd, end, &g.BmpCount); err != nil {
		return err
	}
	if err := binary.Read(rd, end, &g.Size); err != nil {
		return err
	}
	if g.HasPalette {
		g.Palette = &PaletteSection{}
		if err := g.Palette.Decode(rd); err != nil {
			return err
		}
	}
	if err := discardN(rd, 4*int(g.BmpCount)); err != nil {
		return err
	}
	g.Images = make([]*Image, int(g.BmpCount))
	for i := range g.Images {
		g.Images[i] = &Image{Bpp: g.Bpp}
		if err := g.Images[i].Decode(rd, g); err != nil {
			return err
		}
	}
	return nil
}
