package savedb

import (
	"app.yhyue.com/moapp/jybase/mongodb"
	"bp.jydev.jianyu360.cn/BaseService/gateway/common/db"
	"log"
	"sync"
	"time"
)

type DbLogs struct {
	Cache []map[string]interface{}
	lock  sync.Mutex
	Db    mongodb.MongodbSim
}

//SaveLogTask 定时保存日志
func (s *DbLogs) SaveLogTask() {
	s.lock.Lock()
	if len(s.Cache) >= 1 {
		tmp := s.Cache
		s.Cache = make([]map[string]interface{}, 0)
		go func() {
			log.Println("timer..save..visit..log", len(tmp))
			db.MgoLog.SaveBulk("jy_gateway_logs", tmp...)
		}()
	}

	s.lock.Unlock()
	time.AfterFunc(5*time.Minute, s.SaveLogTask)
}

func (s *DbLogs) AddLogToTask(data map[string]interface{}) {
	s.lock.Lock()
	s.Cache = append(s.Cache, data)
	if len(s.Cache) >= 5 {
		tmp := s.Cache
		s.Cache = make([]map[string]interface{}, 0)
		go func() {
			log.Println("save..visit..log", len(tmp), s.Db.SaveBulk("jy_gateway_logs", tmp...))
		}()
	}
	s.lock.Unlock()
}
