package main

import (
	"fmt"

	"mongo.games.com/goserver/core/basic"
	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/task"

	"mongo.games.com/game/common"
	"mongo.games.com/game/model"
	"mongo.games.com/game/worldsrv/internal"
)

func SaveInviteScore(data *model.InviteScore) {
	if data == nil {
		return
	}
	var err error
	task.New(nil, task.CallableWrapper(func(o *basic.Object) interface{} {
		err = model.SaveInviteScore(data)
		if err != nil {
			logger.Logger.Errorf("SaveInviteScore error:%v", err)
			return err
		}
		// 后台统计积分记录
		data.Ts /= 1000000000 // 后台需要秒
		LogChannelSingleton.WriteLog(data)
		logger.Logger.Tracef("==> php InviteScore %+v", *data)
		return nil
	}), task.CompleteNotifyWrapper(func(i interface{}, t task.Task) {
		p := PlayerMgrSington.GetPlayerBySnId(data.InviteSnId)
		if err == nil && p != nil && data.Score != 0 {
			if data.Score < 0 {
				if -data.Score > p.InviteScore {
					data.Score = -p.InviteScore
				}
			}
			p.InviteScore += data.Score
			p.dirty = true

			// 更新邀请任务进度
			if data.Score > 0 {
				TaskSubjectSingleton.Touch(common.TaskTypeInviteScore, &TaskData{
					SnId: p.SnId,
					Num:  data.Score,
				})
			}
		}
	})).StartByFixExecutor(fmt.Sprintf("invite_score_%v", data.InviteSnId))
}

func GetInviteScore(platform string, snid int32) {
	var n, z int64
	var err error
	task.New(nil, task.CallableWrapper(func(o *basic.Object) interface{} {
		n, z, err = model.GetInviteScore(platform, snid)
		if err != nil {
			logger.Logger.Errorf("GetInviteScore error:%v", err)
			return err
		}
		return nil
	}), task.CompleteNotifyWrapper(func(i interface{}, t task.Task) {
		p := PlayerMgrSington.GetPlayerBySnId(snid)
		if err == nil && p != nil {
			p.InviteScore = n
			p.dirty = true

			// 更新邀请任务进度
			p.ResetTaskN(common.TaskTypeInviteScore)
			TaskSubjectSingleton.Touch(common.TaskTypeInviteScore, &TaskData{
				SnId: p.SnId,
				Num:  z,
			})
		}
	})).StartByFixExecutor(fmt.Sprintf("invite_score_%v", snid))
}

type InviteCode struct {
	internal.BasePlayerLoader
}

func (i *InviteCode) LoadAfter(platform string, snid int32) *internal.PlayerLoadReplay {
	n, err := model.GetInviteNum(platform, snid)
	return &internal.PlayerLoadReplay{
		Platform: platform,
		Snid:     snid,
		Err:      err,
		Data:     n,
	}
}

func (i *InviteCode) CallbackAfter(ret *internal.PlayerLoadReplay) {
	if ret == nil {
		return
	}
	p := PlayerMgrSington.GetPlayerBySnId(ret.Snid)
	if p == nil {
		return
	}
	p.InviteNum = ret.Data.(int32)
	p.ResetTaskN(common.TaskTypeInviteNum)
	TaskSubjectSingleton.Touch(common.TaskTypeInviteNum, &TaskData{SnId: p.SnId, Num: int64(p.InviteNum)})
	GetInviteScore(ret.Platform, ret.Snid)
}

func init() {
	internal.RegisterPlayerLoad(new(InviteCode))
}
