package controller

import (
	mhayaGin "github.com/mhaya/components/gin"
	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/internal/constant"
	"github.com/mhaya/game/game_cluster/internal/data"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"github.com/mhaya/game/game_cluster/internal/param"
	mhayaLogger "github.com/mhaya/logger"
)

func (p *Controller) login(c *mhayaGin.Context) {
	var pa param.LoginReq
	if err := c.BindJSON(&pa); err != nil {
		mhayaLogger.Warnf("if login err {. params=%s", pa)
		code.RenderResult(c, code.Error)
		return
	}

	token, err := p.Auth(c)
	if code.IsFail(err) {
		mhayaLogger.Warnf("if login token err {. params=%s", c.GetHeader(constant.Token))
		code.RenderResult(c, code.AccountTokenValidateFail)
		return
	}
	rsp := &models.Player{}
	token.Nickname = pa.NickName
	errCode := p.CallWait(token.TargetPath, "login", token, rsp)
	if code.IsFail(errCode) {
		mhayaLogger.Warnf("[Login] token = %s, errCode = %v", token, errCode)
		code.RenderResult(c, errCode)
		return
	}

	ret := data.AchieveTaskConfig.GetAll()

	for _, v := range rsp.AchieveTask {
		if v.Type == 1 {
			rsp.AchieveTask[v.ID].Url = ret[v.ID].Url
		}

	}

	code.RenderResult(c, code.OK, rsp)
}

func (p *Controller) start(c *mhayaGin.Context) {
	token, err := p.Auth(c)
	if code.IsFail(err) {
		mhayaLogger.Warnf("if start token err {. params=%s", c.GetHeader(constant.Token))
		code.RenderResult(c, code.AccountTokenValidateFail)
		return
	}

	rsp := &models.Player{}
	errCode := p.CallWait(token.TargetPath, "start", nil, rsp)

	if code.IsFail(errCode) {
		mhayaLogger.Warnf("[start] token = %v, errCode = %v", token, errCode)
		code.RenderResult(c, errCode)
		return
	}

	ret := data.AchieveTaskConfig.GetAll()

	for _, v := range rsp.AchieveTask {
		if v.Type == 1 {
			rsp.AchieveTask[v.ID].Url = ret[v.ID].Url
		}
	}

	if len(rsp.Password) > 0 {
		rsp.IsSetPwd = true
	}

	code.RenderResult(c, code.OK, rsp)
}
