package events

import (
	"agent/commons/utils"
	"agent/defines/devent/daction"
	"agent/defines/devent/dcategory"
	"encoding/json"
)

func IsThrottleEvent(event IEvent) bool {
	if utils.SliceEqual(event.Category(), []EventCategory{dcategory.Command}) {
		return event.Action() == daction.Throttle
	}
	// Такое возможно, если ивент пришёл в режиме DataOnly
	if event.Kind() == 0 {
		// Тогда нужно проверить его содержимое
		interval, _ := ThrottleInterval(event)
		return interval > 0
	}
	return false
}

type eventThrottleIntervalResult struct {
	Type     string
	Category string
	Action   string

	Opts struct {
		Internval int64
	}
}

func (e eventThrottleIntervalResult) MarshalJSON() ([]byte, error) {
	jsonData := map[string]any{
		"type":     e.Type,
		"category": e.Category,
		"action":   e.Action,
		"opts": map[string]any{
			"interval": e.Opts.Internval,
		},
	}
	return json.Marshal(jsonData)
}

func (e *eventThrottleIntervalResult) UnmarshalJSON(data []byte) error {
	jsonData := map[string]any{}
	if err := json.Unmarshal(data, &jsonData); err != nil {
		return err
	}
	if val, ok := jsonData["type"].(string); ok {
		e.Type = val
	}
	if val, ok := jsonData["category"].(string); ok {
		e.Category = val
	}
	if val, ok := jsonData["action"].(string); ok {
		e.Action = val
	}
	if opts, ok := jsonData["opts"].(map[string]any); ok {
		if intervalVal, ok := opts["interval"].(float64); ok {
			e.Opts.Internval = int64(intervalVal)
		}
	}
	return nil
}

func ThrottleInterval(event IEvent) (interval int64, err error) {
	data, err := event.Data2()
	if err != nil {
		return 0, err
	}
	var res eventThrottleIntervalResult
	if err = json.Unmarshal(data, &res); err != nil {
		return 0, err
	}
	if res.Type == "event" && res.Category == "command" && res.Action == "throttle" {
		return res.Opts.Internval, err
	}
	return 0, nil
}
