package log

import (
	"io"
	"time"

	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
)

type WriteSyncer interface {
	io.Writer
	Sync() error
}

// 得到LogWriter
func getLogWriter(filePath string, period, count int) WriteSyncer {
	warnIoWriter := getWriter(filePath, period, count)
	return addSync(warnIoWriter)
}

// 日志文件切割
func getWriter(filename string, period, count int) io.Writer {
	// 保存日志count天，每period小时分割一次日志
	duration := time.Hour * time.Duration(period)
	var logfile string
	if period >= 24 {
		logfile = filename + "-%Y%m%d"
	} else {
		logfile = filename + "-%Y%m%d%H"
	}
	hook, err := rotatelogs.New(

		logfile,
		rotatelogs.WithLinkName(filename),
		//		rotatelogs.WithMaxAge(duration),
		rotatelogs.WithRotationCount(count),
		rotatelogs.WithRotationTime(duration),
		rotatelogs.WithLocation(time.Local),
	)

	//保存日志30天，每1分钟分割一次日志
	/*
		hook, err := rotatelogs.New(
			filename+"_%Y%m%d%H%M.log",
			rotatelogs.WithLinkName(filename),
			rotatelogs.WithMaxAge(time.Hour*24*30),
			rotatelogs.WithRotationTime(time.Minute*1),
		)
	*/
	if err != nil {
		panic(err)
	}
	return hook
}

func addSync(w io.Writer) WriteSyncer {
	switch w := w.(type) {
	case WriteSyncer:
		return w
	default:
		return writerWrapper{w}
	}
}

type writerWrapper struct {
	io.Writer
}

func (w writerWrapper) Sync() error {
	return nil
}
