package svc

import (
	"net/rpc"

	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"mongo.games.com/goserver/core/logger"

	"mongo.games.com/game/common"
	"mongo.games.com/game/dbproxy/mongo"
	"mongo.games.com/game/model"
)

func OnlineLogsCollection(plt string) *mongo.Collection {
	s := mongo.MgoSessionMgrSington.GetPltMgoSession(plt, model.OnlineLogDBName)
	if s != nil {
		c_onlinelogrec, first := s.DB().C(model.OnlineLogCollName)
		if first {
			c_onlinelogrec.EnsureIndex(mgo.Index{Key: []string{"snid"}, Background: true, Sparse: true})
			c_onlinelogrec.EnsureIndex(mgo.Index{Key: []string{"onlinetype"}, Background: true, Sparse: true})
			c_onlinelogrec.EnsureIndex(mgo.Index{Key: []string{"onlinets"}, Background: true, Sparse: true})
			c_onlinelogrec.EnsureIndex(mgo.Index{Key: []string{"offlinetype"}, Background: true, Sparse: true})
			c_onlinelogrec.EnsureIndex(mgo.Index{Key: []string{"offlinets"}, Background: true, Sparse: true})
		}
		return c_onlinelogrec
	}
	return nil
}

type OnlineLogSvc struct {
}

func (svc *OnlineLogSvc) InsertOnlineLogs(logs []*model.OnlineLog, ret *bool) (err error) {
	for _, log := range logs {
		err = svc.InsertSignleOnlineLog(log, ret)
		if err != nil {
			return
		}
	}
	*ret = true
	return
}

func (svc *OnlineLogSvc) InsertSignleOnlineLog(log *model.OnlineLog, ret *bool) (err error) {
	clog := OnlineLogsCollection(log.Platform)
	if clog == nil {
		return
	}
	if log.LogId == "" {
		logger.Logger.Warn("svc.InsertSignleOnlineLog error, id")
		return
	}

	switch {
	case (log.OnlineType == common.LoginLogTypeLogin || log.OnlineType == common.LoginLogTypeRehold) &&
		log.OfflineType == 0 && log.OnlineTs > 0 && log.OfflineTs == 0:
		// 登录,重连
	case (log.OfflineType == common.LoginLogTypeDrop || log.OfflineType == common.LoginLogTypeLogout) &&
		log.OnlineTs > 0 && log.OfflineTs > 0:
		// 掉线,登出
	default:
		logger.Logger.Warn("svc.InsertSignleOnlineLog error type")
		return
	}
	_, err = clog.Upsert(bson.M{"_id": log.LogId}, log)
	if err != nil {
		logger.Logger.Warn("svc.InsertSignleLoginLog error:", err)
		return
	}
	*ret = true
	return
}

func init() {
	rpc.Register(new(OnlineLogSvc))
}
