package tr

import (
	"runtime"

	"github.com/sirupsen/logrus"
	"github.com/wpajqz/linker"
)

type Checker interface {
	Check() error
}

func ParseParamFail(ctx linker.Context, param interface{}, fs ...func() error) bool {
	if param != nil {
		if Fail(ctx, linker.StatusBadRequest, ctx.ParseParam(param)) {
			return true
		}

		if checker, ok := param.(Checker); ok {
			return Fail(ctx, linker.StatusBadRequest, checker.Check())
		}
	}

	for _, f := range fs {
		if Fail(ctx, linker.StatusBadRequest, f()) {
			return true
		}
	}

	return false
}

func Fail(ctx linker.Context, status int, err error) bool {
	if err == nil {
		return false
	}

	ctx.Error(status, err.Error())

	if status == linker.StatusInternalServerError {
		_, file, line, _ := runtime.Caller(1)
		logrus.WithField("err", err).Errorf("file:%s line:%d", file, line)
	}

	return true
}

func Success(ctx linker.Context, data interface{}) {
	ctx.Success(data)
}