package svc

import (
	"errors"
	"net/rpc"

	"github.com/globalsign/mgo"
	"mongo.games.com/game/dbproxy/mongo"
	"mongo.games.com/game/model"
	"mongo.games.com/goserver/core/logger"
)

var (
	WelfareLogErr = errors.New("log coinex log open failed.")
)

func WelfareLogsCollection(plt string) *mongo.Collection {
	s := mongo.MgoSessionMgrSington.GetPltMgoSession(plt, model.WelfareLogDBName)
	if s != nil {
		c_welfarelogrec, first := s.DB().C(model.WelfareLogCollName)
		if first {
			c_welfarelogrec.EnsureIndex(mgo.Index{Key: []string{"snid"}, Background: true, Sparse: true})
			c_welfarelogrec.EnsureIndex(mgo.Index{Key: []string{"logtype"}, Background: true, Sparse: true})
			c_welfarelogrec.EnsureIndex(mgo.Index{Key: []string{"wtype"}, Background: true, Sparse: true})
			c_welfarelogrec.EnsureIndex(mgo.Index{Key: []string{"-time"}, Background: true, Sparse: true})
			c_welfarelogrec.EnsureIndex(mgo.Index{Key: []string{"channel"}, Background: true, Sparse: true})
			c_welfarelogrec.EnsureIndex(mgo.Index{Key: []string{"oper"}, Background: true, Sparse: true})
			c_welfarelogrec.EnsureIndex(mgo.Index{Key: []string{"seqno"}, Background: true, Sparse: true})
		}
		return c_welfarelogrec
	}
	return nil
}

type WelfareLogSvc struct {
}

func (svc *WelfareLogSvc) InsertWelfareLog(log *model.WelfareLog, ret *bool) (err error) {
	wlog := WelfareLogsCollection(log.Platform)
	if wlog == nil {
		return
	}
	err = wlog.Insert(log)
	if err != nil {
		logger.Logger.Warn("InsertWelfareLog error:", err)
		return
	}

	*ret = true
	return
}

func (svc *WelfareLogSvc) RemoveWelfareLogOne(args *model.RemoveWelfareLogOneArg, ret *bool) (err error) {
	wlog := WelfareLogsCollection(args.Plt)
	if wlog == nil {
		return WelfareLogErr
	}
	err = wlog.RemoveId(args.Id)
	if err != nil {
		logger.Logger.Warn("RemoveWelfareLogOne error:", err)
		return
	}

	*ret = true
	return
}

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