package middleware

import (
	"time"

	"github.com/ngaut/log"
	"github.com/pingcap/schrodinger/notifiermgr/event"
	"github.com/pingcap/schrodinger/notifiermgr/util"
)

func schedule(configPtr *interface{}) Middleware {
	output := make(chan event.Event)
	input := make(chan event.Event)
	rawConfig, ok := (*configPtr).(map[string]interface{})
	if !ok {
		log.Error("Config format error: config of schedule is not a map")
		return nil
	}
	config := util.SimpleMap(rawConfig)

	interval := config.GetInt64("interval")

	if !ok {
		log.Error("Config format error: interval of schedule is not int")
		return nil
	}

	go func() {
		ticker := time.NewTicker(time.Duration(*interval) * time.Second)
		for range ticker.C {
			output <- event.EmptyEvent{}
		}
	}()

	return &RealMiddleware{
		input,
		output,
	}
}
