package handler

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"youngee_b_api/consts"
	"youngee_b_api/model/http_model"
	"youngee_b_api/pack"
	"youngee_b_api/service/selection_service"
	"youngee_b_api/util"
)

func WrapGetAllSelectionHandler(ctx *gin.Context) {
	handler := newGetAllSelectionHandler(ctx)
	baseRun(handler)
}

type AllSelectionHandler struct {
	ctx  *gin.Context
	req  *http_model.GetAllSelectionRequest
	resp *http_model.CommonResponse
}

func (a AllSelectionHandler) getContext() *gin.Context {
	return a.ctx
}

func (a AllSelectionHandler) getResponse() interface{} {
	return a.resp
}

func (a AllSelectionHandler) getRequest() interface{} {
	return a.req
}

func (a AllSelectionHandler) run() {
	condition := pack.GetSelectionSquareCondition(*a.req)
	data, err := selection_service.Selection.SelectionSquare(a.ctx, *a.req, condition)
	if err != nil {
		logrus.WithContext(a.ctx).Errorf("[FindAllSelectionHandler] error GetAllSelection, err:%+v", err)
		util.HandlerPackErrorResp(a.resp, consts.ErrorInternal, consts.DefaultToast)
		return
	}
	a.resp.Data = data
}

func (a AllSelectionHandler) checkParam() error {
	var errs []error
	if a.req.PageNum < 0 || a.req.PageSize <= 0 {
		errs = append(errs, errors.New("page param error"))
	}
	a.req.PageNum--
	if len(errs) != 0 {
		return fmt.Errorf("check param errs:%+v", errs)
	}
	return nil
}

func newGetAllSelectionHandler(ctx *gin.Context) *AllSelectionHandler {
	return &AllSelectionHandler{
		ctx:  ctx,
		req:  http_model.NewGetAllSelectionRequest(),
		resp: http_model.NewGetAllSelectionResponse(),
	}
}
