package middleware

import (
	"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"
)

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

	store, err := util.GetStorageFromConfig(configPtr)
	if err != nil {
		log.Errorf("Error while connecting to database: %s", errors.ErrorStack(err))
		return nil
	}

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

			store.UpdateNotifyTime(ep)
			output <- ep
		}
	}()
	return &RealMiddleware{
		input,
		output,
	}
}
