package nori

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

type PaletteSection struct {
	Version    uint32
	Params     [4]uint32
	Divided    bool
	DataLength uint32
	Palette    [256]color.Color
	MainBound  [2]uint32

	lastSignature [4]byte
}

func (p *PaletteSection) Decode(rd io.Reader) error {
	if _, err := io.ReadFull(rd, p.lastSignature[:]); err != nil {
		return err
	}
	if sig, target := string(p.lastSignature[:]), "PAL_"; sig != target {
		return fmt.Errorf("bad sig: want %s, got %s", target, sig)
	}
	p.Palette = [256]color.Color{}
	if err := binary.Read(rd, end, &p.Version); err != nil {
		return err
	}
	if err := binary.Read(rd, end, p.Params[:]); err != nil {
		return err
	}
	var cast uint32
	if err := binary.Read(rd, end, &cast); err != nil {
		return err
	}
	p.Divided = (cast > 0)
	if err := binary.Read(rd, end, &p.DataLength); err != nil {
		return err
	}
	for i := 0; i < 256; i++ {
		rgb := [3]byte{}
		_, err := io.ReadFull(rd, rgb[:])
		if err != nil {
			return err
		}
		alpha := uint8(0xff)
		if rgb[0] == 0x00 && rgb[1] == 0xff && rgb[2] == 0x00 {
			alpha = 0x00
		}
		if rgb[0] == 0xff && rgb[1] == 0x00 && rgb[2] == 0xff {
			alpha = 0x00
		}
		p.Palette[i] = &color.RGBA{
			rgb[0], rgb[1], rgb[2],
			alpha,
		}
	}
	if p.Divided {
		if err := binary.Read(rd, end, p.MainBound[:]); err != nil {
			return err
		}
	}
	return nil
}
