package logging

import (
	"time"
)

// Create a new log file at 0 am.
func RotateLogs(howOften time.Duration) {
	prefile := StartNewLogger()
	defer func() {
		if prefile != nil {
			prefile.Close()
		}
	}()

	timer := time.NewTimer(calculateTimeSpan(howOften))
	for range timer.C {
		logfile := StartNewLogger()
		timer.Reset(calculateTimeSpan(howOften))
		if prefile != nil {
			prefile.Close()
		}
		prefile = logfile
	}
}

func calculateTimeSpan(howOften time.Duration) time.Duration {
	now := time.Now()
	next := now.Add(howOften)
	next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
	return next.Sub(now)
}
