package nori

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

type Nori struct {
	Version        uint32
	Params         [5]uint32
	AnimationCount uint32
	SizeNoGawi     uint32
	TotalSize      uint32

	Gawi       *GawiSection
	Animations []*Animation
	//AnimationByKey map[string]*Animation

	lastSignature [4]byte
}

func (n *Nori) Decode(r io.Reader) error {
	rd := reflectReader(r)
	n.Gawi = &GawiSection{}
	if _, err := io.ReadFull(rd, n.lastSignature[:]); err != nil {
		return err
	}
	if sig, target := string(n.lastSignature[:]), "NORI"; sig != target {
		return fmt.Errorf("expected header %s, got %s", target, sig)
	}
	if err := binary.Read(rd, end, &n.Version); err != nil {
		return err
	}
	if err := binary.Read(rd, end, n.Params[:]); err != nil {
		return err
	}
	if err := binary.Read(rd, end, &n.AnimationCount); err != nil {
		return err
	}
	if err := binary.Read(rd, end, &n.SizeNoGawi); err != nil {
		return err
	}
	if err := binary.Read(rd, end, &n.TotalSize); err != nil {
		return err
	}
	if err := n.Gawi.Decode(rd); err != nil {
		return err
	}
	if err := discardN(rd, 4*int(n.AnimationCount)); err != nil {
		return err
	}
	n.Animations = make([]*Animation, n.AnimationCount)
	for i := range n.Animations {
		n.Animations[i] = NewAnimation(int(n.Version))
		if err := n.Animations[i].Decode(rd); err != nil {
			return err
		}
	}
	return nil
}
