package tr

import (
	"github.com/wpajqz/linker"
)

type Checker interface {
	Check() error
}

func ParseParamFail(ctx linker.Context, param interface{}, fs ...func() error) bool {
	if param != nil {
		err := ctx.ParseParam(param)
		if err != nil {
			err = TCPError{Status: linker.StatusBadRequest, Msg: err.Error()}

			return Fail(ctx, err)
		}

		if checker, ok := param.(Checker); ok {
			err := checker.Check()
			if err != nil {
				err = TCPError{Status: linker.StatusBadRequest, Msg: err.Error()}

				return Fail(ctx, checker.Check())
			}
		}
	}

	for _, f := range fs {
		err := f()
		if err != nil {
			err = TCPError{Status: linker.StatusBadRequest, Msg: err.Error()}

			return Fail(ctx, err)
		}
	}

	return false
}

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

	status := linker.StatusInternalServerError
	if v, ok := err.(TCPError); ok {
		status = v.Status
	}

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

	return true
}

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