// package idx parses the Idx/WarHammer.idx file.
//
// No, I don't know what it's for yet.
package idx

import (
	"encoding/binary"
	//"fmt"
	"log"
	"os"
	//"strings"
)

type Type1Record struct {
	Offset1  uint32 // Where the type2 for this type1 is to be found
	Unknown1 uint32 // ???
	Offset2  uint32 // Another offset? But what to?
}

type Type2Record struct {
	Unknown1 [4]byte // ???
	Offset   uint32  // Where the type3 for this type2 is to be found
	Unknown2 [4]byte // ??
}

type Type3Record struct {
	First20 [20]byte
	Last78  [78]byte
}

type Idx struct {
	Filename string

	Type1Records [512]Type1Record // Experimentally, there seem to be 512 of these
	Type2Records []Type2Record
	Type3Records []Type3Record
}

func Load(filename string) (*Idx, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}

	defer f.Close()

	out := &Idx{Filename: filename}

	if err := binary.Read(f, binary.LittleEndian, &out.Type1Records); err != nil {
		return nil, err
	}

	for i, rec := range out.Type1Records {
		var off1diff uint32
		var off2diff uint32

		if i > 0 && rec.Offset1 > 0 {
			lastRec := out.Type1Records[i-1]
			off1diff = rec.Offset1 - lastRec.Offset1
			off2diff = rec.Offset2 - lastRec.Offset2
		}

		log.Printf(
			"%.3d: 0x%.6x diff=%.6d %.4d 0x%.6x diff=%.6d",
			i, rec.Offset1, off1diff, rec.Unknown1, rec.Offset2, off2diff,
			//			i,
			//			rec.Unknown1[0], rec.Unknown1[1], rec.Unknown1[2], rec.Unknown1[3],
			//			rec.Unknown1[4], rec.Unknown1[5], rec.Unknown1[6], rec.Unknown1[7],
		)
	}

	return out, nil
}
