package middleware

import (
	"fmt"

	"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 destroyAlert(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))
	}

	baseDomain := config.GetString("baseDomain")
	if baseDomain == 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
			}
			reportContent := genDestroyText(ep, *baseDomain)

			output <- Notification{
				Content: reportContent,
			}
		}
	}()

	return &RealMiddleware{
		input,
		output,
	}
}

func genDestroyText(ep *types.ExperimentProcess, baseDomain string) string {
	return fmt.Sprintf(
		destroyTextTemplate,
		ep.Creator, baseDomain, ep.BoxID, ep.ID, ep.BoxName, ep.Name,
	)
}

const destroyTextTemplate = `@%s <https://%s/#/experimentdetail?boxid=%d&experimentid=%d|Box *%s* Experiment *%s*> is *destroyed* now.`
