package middleware

import (
	"github.com/jmoiron/sqlx"
	"github.com/juju/errors"
	"github.com/ngaut/log"
	"github.com/pingcap/schrodinger/notifiermgr/event"
	"github.com/pingcap/schrodinger/notifiermgr/util"
)

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

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

	sql := config.GetString("sql")
	if sql == nil {
		log.Warn("SQL config for sql driver is nil")
		return nil
	}

	driver := config.GetString("driver")
	if driver == nil {
		return nil
	}

	datasource := config.GetString("datasource")
	if datasource == nil {
		return nil
	}

	maxIdleConnection := config.GetInt64("max-idle-conns")
	if maxIdleConnection == nil {
		return nil
	}

	db, err := sqlx.Connect(*driver, *datasource)
	if err != nil {
		log.Error("Error while connecting to database %s", errors.ErrorStack(err))
		return nil
	}

	db.SetMaxIdleConns(int(*maxIdleConnection))

	if err != nil {
		log.Errorf("Error while connecting storage: %s", errors.ErrorStack(err))
	}

	go func() {
		for range input {
			rows, err := db.Queryx(*sql)

			if err != nil {
				log.Errorf("Error while executing %s: %s", *sql, errors.ErrorStack(err))
			}

			output <- &rows
		}
	}()

	return &RealMiddleware{
		input,
		output,
	}
}
