package subscriber

import (
	"context"
	"fmt"
	"git.nspix.com/golang/micro/broker"
	"reflect"
)

type Memory struct {
	Id    string
	topic string
	cb    broker.HandleFunc
}

func (sub *Memory) ID() string {
	return sub.Id
}

func (sub *Memory) HasTopic(topic string) bool {
	return sub.topic == topic || sub.topic == "ALL"
}

func (sub *Memory) OnAttach() (err error) {
	return
}

func (sub *Memory) Process(ctx context.Context, e *broker.Event) (err error) {
	if sub.cb != nil {
		err = sub.cb(ctx, e)
	}
	return
}

func (sub *Memory) OnDetach() (err error) {
	return
}

func NewMemorySubscriber(topic string, cb broker.HandleFunc) *Memory {
	id := topic + ":" + fmt.Sprint(reflect.ValueOf(cb).Pointer())
	return &Memory{
		Id:    id,
		topic: topic,
		cb:    cb,
	}
}