package rotater

import (
	"sync"
	"amuz.es/src/infra/goutils/logger"
	"github.com/lestrrat-go/file-rotatelogs"
)

type Option = rotatelogs.Option

type rotateSyncer struct {
	setOnceOnclose *sync.Once
	onClose        func()
	*rotatelogs.RotateLogs
}

func NewRotater(filename string, options ...Option) (logger.RotateSyncer, error) {
	if rotateLogger, err := rotatelogs.New(filename, options...); err != nil {
		return nil, err
	} else {
		return &rotateSyncer{
			setOnceOnclose: &sync.Once{},
			RotateLogs:     rotateLogger,
		}, nil
	}
}
func (r *rotateSyncer) SetOnClose(closeFunc func()) {
	r.setOnceOnclose.Do(func() {
		r.onClose = closeFunc
	})
}

func (r *rotateSyncer) Rotate() error {
	return r.RotateLogs.Rotate()
}
func (r *rotateSyncer) Close() error {
	defer func() {
		if r.onClose != nil {
			r.onClose()
		}
	}()
	return r.RotateLogs.Close()
}

func (r *rotateSyncer) Sync() error {
	return nil
}

func (s *rotateSyncer) Write(bs []byte) (int, error) {
	return s.RotateLogs.Write(bs)
}
