package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"io"
	"miads/adslib"
	"miads/adslib/ads_redis"
	"os"
	"time"

	"github.com/fvbock/endless"
	log "github.com/sirupsen/logrus"
)

func setupLogger(logName string, logLevel log.Level) {
	writer, err := rotatelogs.New(
		logName+".%Y%m%d",

		// WithLinkName为最新的日志建立软连接，以方便随着找到当前日志文件
		rotatelogs.WithLinkName(logName),

		// WithRotationTime设置日志分割的时间，这里设置为一小时分割一次
		rotatelogs.WithRotationTime(time.Hour),

		// WithMaxAge和WithRotationCount二者只能设置一个，
		// WithMaxAge设置文件清理前的最长保存时间，
		// WithRotationCount设置文件清理前最多保存的个数。
		rotatelogs.WithMaxAge(time.Hour*24*3),
	)

	if err != nil {
		log.Errorf("config local file system for logger error: %v", err)
	}

	log.SetReportCaller(true)
	log.SetLevel(logLevel)
	log.SetOutput(io.MultiWriter(writer, os.Stdout))
}

func setupRouter() *gin.Engine {
	r := gin.Default()

	r.POST("/ads", adsHandler)
	return r
}

func main() {
	ads_redis.Setup()
	adslib.GetConf()
	setupLogger(adslib.GetConf().LogPath+"/ads.log", log.TraceLevel)

	if ads_redis.RedisConn.ActiveCount() == 0 {
		fmt.Printf("setup redis failed, no active redis")
		return
	}

	r := setupRouter()
	endless.ListenAndServe(":8080", r)
}
