// Code generated by eventsource-protobuf. DO NOT EDIT.
// source: events.proto

package main

import (
	"fmt"
	"time"

	"github.com/altairsix/eventsource"
	"github.com/gogo/protobuf/proto"
)

type serializer struct {
}

func (s *serializer) MarshalEvent(event eventsource.Event) (eventsource.Record, error) {
	container := &ShoppingCart{}

	switch v := event.(type) {

	case *ItemAdded:
		container.Type = 2
		container.A = v

	case *ItemRemoved:
		container.Type = 3
		container.B = v

	default:
		return eventsource.Record{}, fmt.Errorf("Unhandled type, %v", event)
	}

	data, err := proto.Marshal(container)
	if err != nil {
		return eventsource.Record{}, err
	}

	return eventsource.Record{
		Version: event.EventVersion(),
		Data:    data,
	}, nil
}

func (s *serializer) UnmarshalEvent(record eventsource.Record) (eventsource.Event, error) {
	container := &ShoppingCart{};
	err := proto.Unmarshal(record.Data, container)
	if err != nil {
		return nil, err
	}

	var event interface{}
	switch container.Type {

	case 2:
		event = container.A

	case 3:
		event = container.B

	default:
		return nil, fmt.Errorf("Unhandled type, %v", container.Type)
	}

	return event.(eventsource.Event), nil
}

func NewSerializer() eventsource.Serializer {
	return &serializer{}
}

func (m *ItemAdded) AggregateID() string { return m.Id }
func (m *ItemAdded) EventVersion() int   { return int(m.Version) }
func (m *ItemAdded) EventAt() time.Time  { return time.Unix(m.At, 0) }

func (m *ItemRemoved) AggregateID() string { return m.Id }
func (m *ItemRemoved) EventVersion() int   { return int(m.Version) }
func (m *ItemRemoved) EventAt() time.Time  { return time.Unix(m.At, 0) }

