package pbmsg

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io/ioutil"

	"github.com/golang/protobuf/proto"
)

// EventSet. It correctly handles decompressing the EventSet if it is
// compressed.
func UnpackEventSet(es *EventSet) ([]*Event, error) {
	switch es.GetCompression() {
	case Compression_NONE:
		return es.Event, nil
	case Compression_GZIP:
		gzr, err := gzip.NewReader(bytes.NewReader(es.CompressedEventSet))
		if err != nil {
			return nil, err
		}
		uncomp, err := ioutil.ReadAll(gzr)
		if err != nil {
			return nil, err
		}
		es = &EventSet{}
		err = proto.Unmarshal(uncomp, es)
		if err != nil {
			return nil, err
		}
		return UnpackEventSet(es)
	default:
		return nil, fmt.Errorf("unexpected compression, value=%d", es.GetCompression())
	}
}
