package processor

import (
	"bytes"
	"context"
	"fmt"
	"text/template"

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

func init() {
	RegisterProcessor(ProcessorRegistration{
		Type:  "string.create",
		Title: "Create String",
		ParamsSchema: &jsonschema.Schema{
			Type: "object",
			Properties: map[string]*jsonschema.Schema{
				"template": {
					Title:       "Template",
					Description: "template to evaluate",
					Type:        "string",
				},
			},
			Required:             []string{"template"},
			AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
		},
		New: func(config config.ProcessorConfig) (Processor, error) {
			params := config.Params
			templateString, err := params.GetString("template")
			if err != nil {
				return nil, fmt.Errorf("string.create template error: %w", err)
			}

			templateTemplate, err := template.New("template").Parse(templateString)

			if err != nil {
				return nil, err
			}
			return &StringCreate{config: config, Template: templateTemplate}, nil
		},
	})
}

type StringCreate struct {
	config   config.ProcessorConfig
	Template *template.Template
}

func (sc *StringCreate) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
	templateData := wrappedPayload

	var templateBuffer bytes.Buffer
	err := sc.Template.Execute(&templateBuffer, templateData)

	if err != nil {
		wrappedPayload.End = true
		return wrappedPayload, err
	}

	wrappedPayload.Payload = templateBuffer.String()

	return wrappedPayload, nil
}

func (sc *StringCreate) Id() string {
	return sc.config.Id
}

func (sc *StringCreate) Type() string {
	return sc.config.Type
}
