package processor

import (
	"context"
	"errors"

	"github.com/jwetzell/showbridge-go/config"
	"github.com/jwetzell/showbridge-go/internal/common"
)

func init() {
	RegisterProcessor(ProcessorRegistration{
		Type:  "string.decode",
		Title: "Decode String",
		New: func(config config.ProcessorConfig) (Processor, error) {
			return &StringDecode{config: config}, nil
		},
	})
}

type StringDecode struct {
	config config.ProcessorConfig
}

func (sd *StringDecode) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
	payload := wrappedPayload.Payload
	payloadBytes, ok := common.GetAnyAsByteSlice(payload)

	if !ok {
		wrappedPayload.End = true
		return wrappedPayload, errors.New("string.decode processor only accepts a []byte")
	}

	payloadMessage := string(payloadBytes)

	wrappedPayload.Payload = payloadMessage
	return wrappedPayload, nil
}

func (sd *StringDecode) Id() string {
	return sd.config.Id
}

func (sd *StringDecode) Type() string {
	return sd.config.Type
}
