package rotater

import (
	"os"
	"path/filepath"
	"log"
	"amuz.es/src/infra/goutils/logger"
	"github.com/lestrrat-go/file-rotatelogs"
)

var loggers RotateSyncerSet

func NewLogWriter(FileName string, logDir string, options ...Option) (logger.RotateSyncer, error) {
	switch FileName {
	case "Stdout":
		return NewLocked(os.Stdout), nil
	case "Stderr":
		return NewLocked(os.Stderr), nil
	default:
		logpath := FileName
		if logDir != "" {
			logpath = filepath.Join(logDir, FileName)
		}
		logpath,_ = filepath.Abs(logpath)
		log.Println(" Attention!! log writes to ", logpath)
		options=append(options,rotatelogs.WithLinkName(logpath))
		if logWriter, err := NewRotater(logpath+".%Y%m%d", options...); err != nil {
			return nil, err
		} else {
			loggers.Store(logWriter)
			logWriter.SetOnClose(func() { loggers.Delete(logWriter) })
			return logWriter, nil
		}
	}
}

func Rotate() {
	loggers.Range(func(rotater logger.RotateSyncer) {
		rotater.Sync()
		rotater.Rotate()
	})
	log.Println("rotated")
}

func Close() {
	loggers.Range(func(rotater logger.RotateSyncer) {
		rotater.Sync()
		rotater.Close()
	})
	log.Println("end of log")
}
