package middleware

import (
	"time"

	"github.com/juju/errors"
	"github.com/ngaut/log"
	"github.com/pingcap/schrodinger/notifiermgr/event"
	"github.com/pingcap/schrodinger/notifiermgr/util"
	"github.com/pingcap/schrodinger/pkg/types"
	globalUtil "github.com/pingcap/schrodinger/util"
)

func matchTooEarlyExp(configPtr *interface{}) Middleware {
	input := make(chan event.Event)
	output := make(chan event.Event)

	config, err := util.GetSimpleMap(configPtr)
	if err != nil {
		log.Errorf("Error while mapping a config to map: %s", errors.ErrorStack(err))
	}

	threshold := config.GetInt64("time")
	if threshold == nil {
		return nil
	}

	go func() {
		for ev := range input {
			ep, ok := ev.(*types.ExperimentProcess)
			if !ok {
				log.Error("Input of generateExpReportDriver is not an *ExperimentProcess")
				continue
			}

			startTime, err := time.Parse(globalUtil.TimeFormat, ep.StartTime)
			if err != nil {
				log.Errorf("Error while parsing time %s", errors.ErrorStack(err))
			}
			if time.Now().Sub(startTime) > time.Duration(*threshold)*time.Hour {
				output <- ep
			}
		}
	}()

	return &RealMiddleware{
		input,
		output,
	}
}
