package main

import (
	"../log"
	"../mod"
	"../utils"
	"encoding/json"
	"go.uber.org/zap"
	"time"
)

type userGameHist struct {
	GameId int64 `json:"gameId"` // 游戏
	Delta  int64 `json:"delta"`  // 金币变动
}

type userActive struct {
	Ts      int64           `json:"ts"` // 最后操作时间
	GameId  int64           `json:"gameId"`
	Balance int64           `json:"balance"`
	History []*userGameHist `json:"history"`
}

func NewUserActive() *userActive {
	// 返回一个新状态，相当于重置
	return &userActive{
		Ts:      time.Now().Unix(),
		GameId:  0,
		Balance: 0,
	}
}

// 有则有，没有返回默认
func _getUserActive(guid uint64) (*userActive, error) {
	s, err := mod.GetUserActive(guid)
	if err != nil {
		return nil, err
	}
	ua := NewUserActive()
	if len(s) <= 0 {
		return ua, nil
	}
	err = json.Unmarshal([]byte(s), ua)
	if nil != err {
		return nil, err
	}
	now := time.Now().Unix()
	if !utils.TheSameDay(now, ua.Ts) {
		ua.Reset()
	}
	return ua, nil
}

func _setUserActive(guid uint64, ua *userActive) error {
	bytes, err := json.Marshal(ua)
	if err != nil {
		return err
	}
	return mod.UpdateUserActive(guid, string(bytes))
}

func (self *userActive) Reset() {
	self.Ts = time.Now().Unix()
	self.GameId = 0
	self.Balance = 0
	self.History = make([]*userGameHist, 0)
}

func UA_OnEnterGame(guid uint64, gameId int64, balance int64) {
	ua, err := _getUserActive(guid)
	// 无论之前在不在游戏中，都相当于重置，放弃之前的状态
	if err != nil {
		log.Error("OnEnterGame", zap.Uint64("guid", guid),
			zap.Error(err), zap.Int64("gameId", gameId))
		return
	}
	ua.Ts = time.Now().Unix()
	ua.Balance = balance
	ua.GameId = gameId

	err = _setUserActive(guid, ua)
	if nil != err {
		log.Error("OnEnterGame", zap.Uint64("guid", guid),
			zap.Error(err))
	}
}

func UA_OnLeaveGameOrOffline(guid uint64, balance int64) {
	ua, err := _getUserActive(guid)
	if err != nil {
		log.Error("OnLeaveGameOrOffline", zap.Uint64("guid", guid),
			zap.Error(err))
		return
	}
	if ua.GameId == 0 {
		log.Warn("OnLeaveGameOrOffline", zap.Uint64("guid", guid))
		return
	}
	delta := balance - ua.Balance
	if delta != 0 || time.Now().Unix()-ua.Ts >= 300 {
		ua.History = append(ua.History, &userGameHist{
			GameId: ua.GameId,
			Delta:  delta,
		})
	}

	ua.GameId = 0
	ua.Ts = time.Now().Unix()
	ua.Balance = balance

	err = _setUserActive(guid, ua)
	if err != nil {
		log.Error("OnLeaveGameOrOffline", zap.Uint64("guid", guid),
			zap.Error(err))
	}
}

func UA_IsTodayActive(guid uint64) bool {
	ua, err := _getUserActive(guid)
	if err != nil {
		log.Error("OnLeaveGameOrOffline", zap.Uint64("guid", guid),
			zap.Error(err))
		return false
	}
	return len(ua.History) > 0
}
