package gen7

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"strings"
	"unicode/utf16"

	p "github.com/ajswis/go-pkparse-server/pokemon"
)

// Parse accepts a raw pokemon (byte slice) and either returns a Pokemon struct
// with all applicable fields populated or an error depicting the reason for
// failure.
func Parse(rawPokemon p.RawPokemon) (*p.Pokemon, error) {
	if l := len(rawPokemon); l < 232 {
		return nil, fmt.Errorf("Invalid length for generation 7 pokemon: %d bytes", l)
	}

	var pkmn p.Pokemon
	pkmn.PokedexNumber = binary.LittleEndian.Uint16(rawPokemon[0x08:])
	pkmn.RawNickname = rawPokemon[0x40:0x58]
	pkmn.Nickname = binaryToUTF16leString(pkmn.RawNickname)
	pkmn.RawPokemon = &rawPokemon

	return &pkmn, nil
}

func binaryToUTF16leString(b []byte) string {
	r := bytes.NewReader(b)
	u16 := make([]uint16, len(b)/2)
	binary.Read(r, binary.LittleEndian, &u16)
	runes := utf16.Decode(u16)
	s := strings.Split(string(runes), "\u0000")[0]

	return s
}
