package rotater

import (
	"sync"
	"amuz.es/src/infra/goutils/logger"
)

type LockedWriteSyncer struct {
	sync.Mutex
	ws logger.WriteSyncer
}

// Lock wraps a WriteSyncer in a mutex to make it safe for concurrent use. In
// particular, *os.Files must be locked before use.
func NewLocked(ws logger.WriteSyncer) logger.RotateSyncer {
	if lws, ok := ws.(*LockedWriteSyncer); ok {
		// no need to layer on another lock
		return lws
	}
	return &LockedWriteSyncer{ws: ws}
}

func (s *LockedWriteSyncer) Write(bs []byte) (int, error) {
	s.Lock()
	n, err := s.ws.Write(bs)
	s.Unlock()
	return n, err
}

func (s *LockedWriteSyncer) Sync() error {
	s.Lock()
	err := s.ws.Sync()
	s.Unlock()
	return err
}

func (r *LockedWriteSyncer) SetOnClose(closeFunc func()) {}
func (r *LockedWriteSyncer) Rotate() (err error)         { return }
func (r *LockedWriteSyncer) Close() (err error)          { return }
