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
	}

	ctl, ok := p.GetChildActor(token.PlayerID)
	if !ok {
		code.RenderResult(c, code.Error)
		return
	}

	rsp := &models.Player{}
	token.Nickname = pa.NickName
	errCode := ctl.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
		}
	}

	var curId int
	for _, v := range rsp.AchieveTask {
		if v.Type == 2 {
			if v.Num == v.Condition.Max {
				continue
			}
			if curId == 0 {
				curId = v.ID
			}
			if v.ID < curId {
				curId = v.ID
			}
		}
	}

	for _, v := range rsp.AchieveTask {
		if v.Type == 2 {
			if v.ID != curId {
				delete(rsp.AchieveTask, v.ID)
			}
		}
	}

	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
	}

	ctl, ok := p.GetChildActor(token.PlayerID)
	if !ok {
		code.RenderResult(c, code.Error)
		return
	}

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

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

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