package plugin_sei

import (
	"context"
	"encoding/base64"
	"errors"

	globalPB "m7s.live/v5/pb"
	"m7s.live/v5/pkg/config"
	pb "m7s.live/v5/plugin/sei/pb"
	sei "m7s.live/v5/plugin/sei/pkg"
)

func (conf *SEIPlugin) Insert(ctx context.Context, req *pb.InsertRequest) (*globalPB.SuccessResponse, error) {
	streamPath := req.StreamPath
	targetStreamPath := req.TargetStreamPath
	if targetStreamPath == "" {
		targetStreamPath = streamPath + "/sei"
	}
	publisher, err := conf.Server.GetPublisher(streamPath)
	if err != nil {
		return nil, err
	}
	var transformer *sei.Transformer
	if tm, ok := conf.Server.Transforms.Get(targetStreamPath); ok {
		transformer, ok = tm.TransformJob.Transformer.(*sei.Transformer)
		if !ok {
			return nil, errors.New("targetStreamPath is not a sei transformer")
		}
	} else {
		transformer = sei.NewTransform().(*sei.Transformer)
		transformer.TransformJob.Init(transformer, &conf.Plugin, publisher, config.Transform{
			Output: []config.TransfromOutput{
				{
					Target:     targetStreamPath,
					StreamPath: targetStreamPath,
				},
			},
		}).WaitStarted()
	}
	t := req.Type
	var data []byte
	switch req.Format {
	case "json", "string":
		data = []byte(req.Data)
		data = []byte(req.Data)
	case "base64":
		data, err = base64.StdEncoding.DecodeString(req.Data)
	}
	transformer.AddSEI(byte(t), data)
	err = transformer.WaitStarted()
	if err != nil {
		return nil, err
	}
	return &globalPB.SuccessResponse{
		Code:    0,
		Message: "success",
	}, nil
}
