package game

import (
	"encoding/json"
	kafkaMiddleware "server/middleware/kafka"
	"sync"

	"github.com/robfig/cron/v3"
)

const (
	Login_log    = 1
	LoginOut_log = 2
	Event_log    = 3
)
const (
	PLAYROOM_LOST = "playroom_lost"
	LOG_LENGTH    = 10000
)

type LogMgr struct {
	L         []*Log
	McronSave *cron.Cron
	Lock      sync.Mutex
}

type Log struct {
	Uid       int64
	AppId     int
	ServerId  int
	EventName string
	Param     map[string]interface{}
	TimeStamp int64
}

func (L *LogMgr) InitManager() {
	L.McronSave = cron.New()
	L.L = make([]*Log, 0, LOG_LENGTH)
	L.McronSave.AddFunc("@every 10s", func() {
		L.Lock.Lock()
		defer L.Lock.Unlock()
		if kafkaMiddleware.KafkaMod == nil {
			if len(L.L) > LOG_LENGTH {
				L.L = L.L[:0]
			} else if len(L.L) > LOG_LENGTH {
				L.L = L.L[len(L.L)-LOG_LENGTH:]
			}
			return
		}
		Quene := L.L
		NewQuene := make([]*Log, 0, LOG_LENGTH)
		for _, v := range Quene {
			value, _ := json.Marshal(v)
			err := kafkaMiddleware.SendMsg([]byte(v.EventName), value)
			if err != nil {
				NewQuene = append(NewQuene, v)
			}
		}
		L.L = NewQuene
	})
	L.McronSave.Start()
}

func (L *LogMgr) AddLog(logs *Log) {
	L.Lock.Lock()
	defer L.Lock.Unlock()
	L.L = append(L.L, logs)
}

func (L *LogMgr) Close() {
	L.McronSave.Stop()
	L.Lock.Lock()
	defer L.Lock.Unlock()
	for _, v := range L.L {
		value, _ := json.Marshal(v)
		kafkaMiddleware.SendMsg([]byte(v.EventName), value)
	}
	L.L = L.L[:0]
}
