// Creates a janitor. Basically function that triggers periodically the run of another function.
package pkcache

import (
	"fmt"
	"time"
)

// Janitor is structure used for cleaning process.
type Janitor struct {
	RunInterval time.Duration //in seconds
	stop        chan bool
}

// NEWJanitor is constructor for janitor.
func NewJanitor(pRunSecondsInterval int) *Janitor {
	return &Janitor{
		RunInterval: time.Duration(pRunSecondsInterval) * time.Second,
		stop:        make(chan bool),
	}
}

// Clean - to be invoked for cleaning the cache. runs in separate goroutine
func (j *Janitor) Clean(with func()) {
	ticker := time.NewTicker(j.RunInterval)

	go func() {
		for {
			select {
			case <-ticker.C:
				{
					fmt.Println("Janitor Triggered")

					with()
				}

			case <-j.stop:
				{
					ticker.Stop()
					fmt.Println("ticker stopped")

					return
				}
			}
		}
	}()
}

func (j *Janitor) Stop() {
	fmt.Println("Janitor stopping...")

	j.stop <- true
}
