package logrusbun

import (
	
	
	
	
	
	
	

	
	
)

// QueryHookOptions logging options
type QueryHookOptions struct {
	LogSlow         time.Duration
	Logger          logrus.FieldLogger
	QueryLevel      logrus.Level
	SlowLevel       logrus.Level
	ErrorLevel      logrus.Level
	MessageTemplate string
	ErrorTemplate   string
}

// QueryHook wraps query hook
type QueryHook struct {
	opts            QueryHookOptions
	errorTemplate   *template.Template
	messageTemplate *template.Template
}

// LogEntryVars variables made available t otemplate
type LogEntryVars struct {
	Timestamp time.Time
	Query     string
	Operation string
	Duration  time.Duration
	Error     error
}

// NewQueryHook returns new instance
func ( QueryHookOptions) *QueryHook {
	 := new(QueryHook)

	if .ErrorTemplate == "" {
		.ErrorTemplate = "{{.Operation}}[{{.Duration}}]: {{.Query}}: {{.Error}}"
	}
	if .MessageTemplate == "" {
		.MessageTemplate = "{{.Operation}}[{{.Duration}}]: {{.Query}}"
	}
	.opts = 
	,  := template.New("ErrorTemplate").Parse(.opts.ErrorTemplate)
	if  != nil {
		panic()
	}
	,  := template.New("MessageTemplate").Parse(.opts.MessageTemplate)
	if  != nil {
		panic()
	}

	.errorTemplate = 
	.messageTemplate = 
	return 
}

// BeforeQuery does nothing tbh
func ( *QueryHook) ( context.Context,  *bun.QueryEvent) context.Context {
	return 
}

// AfterQuery convert a bun QueryEvent into a logrus message
func ( *QueryHook) ( context.Context,  *bun.QueryEvent) {
	var  logrus.Level
	var  bool
	var  bytes.Buffer

	 := time.Now()
	 := .Sub(.StartTime)

	switch .Err {
	case nil, sql.ErrNoRows:
		 = false
		if .opts.LogSlow > 0 &&  >= .opts.LogSlow {
			 = .opts.SlowLevel
		} else {
			 = .opts.QueryLevel
		}
	default:
		 = true
		 = .opts.ErrorLevel
	}
	if  == 0 {
		return
	}

	 := &LogEntryVars{
		Timestamp: ,
		Query:     string(.Query),
		Operation: eventOperation(),
		Duration:  ,
		Error:     .Err,
	}

	if  {
		if  := .errorTemplate.Execute(&, );  != nil {
			panic()
		}
	} else {
		if  := .messageTemplate.Execute(&, );  != nil {
			panic()
		}
	}

	switch  {
	case logrus.DebugLevel:
		.opts.Logger.Debug(.String())
	case logrus.InfoLevel:
		.opts.Logger.Info(.String())
	case logrus.WarnLevel:
		.opts.Logger.Warn(.String())
	case logrus.ErrorLevel:
		.opts.Logger.Error(.String())
	case logrus.FatalLevel:
		.opts.Logger.Fatal(.String())
	case logrus.PanicLevel:
		.opts.Logger.Panic(.String())
	default:
		panic(fmt.Errorf("Unsupported level: %v", ))
	}

}

// taken from bun
func ( *bun.QueryEvent) string {
	switch .QueryAppender.(type) {
	case *bun.SelectQuery:
		return "SELECT"
	case *bun.InsertQuery:
		return "INSERT"
	case *bun.UpdateQuery:
		return "UPDATE"
	case *bun.DeleteQuery:
		return "DELETE"
	case *bun.CreateTableQuery:
		return "CREATE TABLE"
	case *bun.DropTableQuery:
		return "DROP TABLE"
	}
	return queryOperation(.Query)
}

// taken from bun
func ( string) string {
	if  := strings.Index(, " ");  > 0 {
		 = [:]
	}
	if len() > 16 {
		 = [:16]
	}
	return string()
}