package store

import (
	"github.com/gogo/protobuf/proto"
	"github.com/hashicorp/raft"
	"github.com/sjy-dv/scdb/scdb/pkg/log"
	"github.com/sjy-dv/scdb/scdb/pkg/protobuf/scdbpb"
)

type fsmSnapshot struct {
	db DB
}

func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {
	log.Info("Persist action in fsmSnapshot")
	defer sink.Close()

	ch := f.db.SnapshotItems()
	keyCount := 0

	for {
		buff := proto.NewBuffer([]byte{})
		dataItem := <-ch
		item := dataItem.(*KVItem)
		if item.IsFinished() {
			break
		}

		pvi := &scdbpb.RaftKVItem{
			Key:   item.key,
			Value: item.value,
		}
		keyCount++
		buff.EncodeMessage(pvi)
		if _, err := sink.Write(buff.Bytes()); err != nil {
			return err
		}
	}
	log.Infof("Persist total %d keys", keyCount)
	return nil
}

func (f *fsmSnapshot) Release() {
	log.Info("Release action in fsmSnapshot")
}
