package cache

import (
	"log"
	"time"
)

// Janitor is used to delete expired items from cache.
type Janitor struct {
	ToClean     *Cache
	RunInterval time.Duration // in seconds
	stop        chan bool     // channel used to signalize exit
}

// NEWJanitor - constructor for janitor
func NEWJanitor(toClean *Cache, secondsRunInterval int) *Janitor {
	return &Janitor{
		ToClean:     toClean,
		RunInterval: time.Duration(secondsRunInterval) * time.Second,
		stop:        make(chan bool),
	}
}

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

	go func() {
		for {
			select {
			case <-ticker.C:
				log.Println("deleting")
				j.ToClean.DeleteExpired()

			case <-j.stop:
				ticker.Stop()
				log.Println("ticker stopped")
				return
			}
		}
	}()
}

// Stop - stops janitor goroutine
func (j *Janitor) Stop() {
	j.stop <- true
}
