package filter

import (
	"net/url"

	"github.com/childe/gohangout/field_setter"
	"github.com/childe/gohangout/topology"
	"github.com/childe/gohangout/value_render"
	"k8s.io/klog/v2"
)

type URLDecodeFilter struct {
	config map[any]any
	fields map[field_setter.FieldSetter]value_render.ValueRender
}

func init() {
	Register("URLDecode", newURLDecodeFilter)
}

func newURLDecodeFilter(config map[any]any) topology.Filter {
	plugin := &URLDecodeFilter{
		config: config,
		fields: make(map[field_setter.FieldSetter]value_render.ValueRender),
	}

	if fieldsValue, ok := config["fields"]; ok {
		for _, field := range fieldsValue.([]any) {
			fieldSetter := field_setter.NewFieldSetter(field.(string))
			if fieldSetter == nil {
				klog.Fatalf("could build field setter from %s", field.(string))
			}
			plugin.fields[fieldSetter] = value_render.GetValueRender2(field.(string))
		}
	} else {
		klog.Fatal("fields must be set in URLDecode filter plugin")
	}
	return plugin
}

// 如果字段不是字符串, 返回false, 其它返回true
func (plugin *URLDecodeFilter) Filter(event map[string]any) (map[string]any, bool) {
	success := true
	for s, v := range plugin.fields {
		value, err := v.Render(event)
		if err != nil || value == nil {
			success = false
			continue
		}
		if t, ok := value.(string); !ok {
			success = false
			continue
		} else {
			rst, err := url.QueryUnescape(t)
			if err != nil {
				success = false
				continue
			}
			s.SetField(event, rst, "", true)
		}
	}
	return event, success
}
