package sdf

import (
	"encoding/json"
	"fmt"
	"testing"

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

func TestKeyType(t *testing.T) {
	keyTypes := []KeyType{KeyTypeUnknow,
		KeyTypeBlock,
		KeyTypeSm1,
		KeyTypeSm4,
		KeyTypeSm2Sign,
		KeyTypeSm2Enc,
		KeyTypeSm9MasterSign,
		KeyTypeSm9MasterEnc,
		KeyTypeSm9UserSign,
		KeyTypeSm9UserEnc,
		KeyTypeRsa,
	}
	for _, kt := range keyTypes {
		if GetKeyType(kt.String()) != kt {
			t.Fatal("error:", kt)
		}
	}
}

func TestSnapshot(t *testing.T) {

	SDF := &SdfNoLock{}
	for idx := uint32(0); idx < 10; idx++ {
		refKey := &common.ECCrefPrivateKey{Bits: 256}
		SDF.SDF_GenerateRandom(refKey.K[32:])

		var err error
		err = SDF.ImportSm2KeyAtIndex(idx, KeyTypeSm2Sign, refKey)
		if err != nil {
			panic(err)
		}
		err = SDF.ImportSm2KeyAtIndex(idx, KeyTypeSm2Enc, refKey)
		if err != nil {
			panic(err)
		}
	}
	for idx := uint32(0); idx < 10; idx++ {
		SDF.GenerateKekAtIndex(idx)
	}
	password := []byte("12345")
	snapshot, err := SDF.Snapshot(true, password, 1000)
	if err != nil {
		t.Fatal(err)
	}

	snapshotBytes, err := json.MarshalIndent(snapshot, "", "  ")
	if err != nil {
		t.Fatal(err)
	}

	fmt.Println(string(snapshotBytes))

	var restor Snapshot
	json.Unmarshal(snapshotBytes, &restor)
	err = SDF.Restore(&restor, password)
	if err != nil {
		t.Fatal(err)
	}

	snapshot2, err := SDF.Snapshot(false, []byte("12345"), 1000)
	snapshotBytes2, err := json.MarshalIndent(snapshot2, "", "  ")
	if err != nil {
		t.Fatal(err)
	}
	fmt.Println(string(snapshotBytes2))

}
