package sdf

import (
	"encoding/binary"
	"fmt"

	"xdx.jelly/xgcl/api/common"
)

type DeviceInfo struct {
	IssuerName      [40]byte
	DeviceName      [16]byte
	DeviceSerial    [16]byte
	DeviceVersion   uint32
	StandardVersion uint32
	AsymAlgAbility  [2]uint32
	SymAlgAbility   uint32
	HashAlgAbility  uint32
	BufferSize      uint32
}

func (d *DeviceInfo) Size() int {
	return 40 + 16 + 16 + 4*7
}

func strlen(s []byte) int {
	for i, c := range s {
		if c == 0 {
			return i
		}
	}
	return len(s)
}

func (d *DeviceInfo) String() string {
	return fmt.Sprintf("IssuerName: %s\nDeviceName: %s\nDeviceSerial: %s\nDeviceVersion: 0x%08x\nStandardVersion: 0x%08x\nAsymAlgAbility: 0x%08x%08x\nSymAlgAbility 0x%08x\nHashAlgAbility 0x%08x\nBufferSize: 0x%08x",
		string(d.IssuerName[:strlen(d.IssuerName[:])]),
		string(d.DeviceName[:strlen(d.DeviceName[:])]),
		string(d.DeviceSerial[:strlen(d.DeviceSerial[:])]),
		d.DeviceVersion,
		d.StandardVersion,
		d.AsymAlgAbility[0],
		d.AsymAlgAbility[1],
		d.SymAlgAbility,
		d.HashAlgAbility,
		d.BufferSize)
}

func (d *DeviceInfo) Unmarshal(data []byte) error {
	fmt.Println(data)
	if len(data) < d.Size() {
		return common.SDR_INARGERR
	}
	n := copy(d.IssuerName[:], data)
	data = data[n:]
	n = copy(d.DeviceName[:], data)
	data = data[n:]
	n = copy(d.DeviceSerial[:], data)
	data = data[n:]
	d.DeviceVersion = binary.LittleEndian.Uint32(data)
	data = data[4:]
	d.StandardVersion = binary.LittleEndian.Uint32(data)
	data = data[4:]
	d.AsymAlgAbility[0] = binary.LittleEndian.Uint32(data)
	data = data[4:]
	d.AsymAlgAbility[1] = binary.LittleEndian.Uint32(data)
	data = data[4:]
	d.SymAlgAbility = binary.LittleEndian.Uint32(data)
	data = data[4:]
	d.HashAlgAbility = binary.LittleEndian.Uint32(data)
	data = data[4:]
	d.BufferSize = binary.LittleEndian.Uint32(data)
	return nil
}

var (
	devInfo = &DeviceInfo{
		IssuerName:      [40]byte{'G', 'o', 'M', 'a', 'i', 'n'},
		DeviceName:      [16]byte{'G', 'C', 'L'},
		DeviceSerial:    [16]byte{'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
		DeviceVersion:   1,
		StandardVersion: 1,
		AsymAlgAbility:  [2]uint32{10000, 10000},
		SymAlgAbility:   10000,
		HashAlgAbility:  10000,
		BufferSize:      1024, // 最大随机数长度
	}
)
