package backend

import (
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/pkg/util"
	"bwallet/service/live_info_service"
	"bwallet/service/live_title_record_service"
	"bwallet/validate_service"
	"github.com/Unknwon/com"
	"github.com/gin-gonic/gin"
	"strings"
)

func GetLiveTitleRecord(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

	var platform_id int
	platform_id = user.UserInfo.PlatformId
	if ("administrator" == group) {
		if arg := c.Query("platform_id"); arg != "" {
			platform_id = com.StrTo(c.Query("platform_id")).MustInt()
		}
	}
	status := com.StrTo(c.DefaultQuery("status", "0")).MustUint8()
	recordService := live_title_record_service.LiveTitleRecord{
		Status:     status,
		PlatformId: int64(platform_id),
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

	total, err := recordService.Count()
	if err != nil {
		handler.SendResponse(c, errno.ErrCountLiveTitleRecord, nil)
		return
	}

	record, err := recordService.GetAll()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	data := make(map[string]interface{})
	data["items"] = record
	data["total"] = total

	handler.SendResponse(c, nil, data)
}

func VerifyLiveTitleRecord(c *gin.Context) {
	record := validate_service.VerifyLiveTitleRecord{}
	c.ShouldBindJSON(&record)

	if ok, errors := validate_service.ValidateInputs(record); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	recordService := live_title_record_service.LiveTitleRecord{
		Id:     record.Id,
		Status: record.Status,
	}

	if err := recordService.Verify(); err != nil {
		handler.SendResponse(c, errno.ErrUpdateLiveTitleRecord, nil)
		return
	}

	if 1 == record.Status {
		recordService := live_title_record_service.LiveTitleRecord{Id: record.Id}

		record_info, err := recordService.GetRecord()
		if err != nil {
			handler.SendResponse(c, errno.InternalServerError, nil)
			return
		}

		infoService := live_info_service.LiveInfo{
			Id:    record_info.LiveId,
			Title: record_info.NewTitle,
		}

		if err := infoService.TitleUpdate(); err != nil {
			handler.SendResponse(c, errno.ErrUpdateLiveInfo, nil)
			return
		}
	}

	handler.SendResponse(c, nil, nil)
}
