package bulk

import (
	"time"

	"github.com/gorhill/cronexpr"

	"code.justin.tv/d8a/buddy/lib/config"
)

type Schedule struct {
	Crons []*cronexpr.Expression
}

func NewSchedule(schedule []config.BulkSchedule) *Schedule {
	newSchedule := new(Schedule)

	for _, scheduleItem := range schedule {
		newSchedule.Crons = append(newSchedule.Crons, cronexpr.MustParse(scheduleItem.CronSchedule))
	}

	return newSchedule
}

func (schedule *Schedule) NextRun(currentTime time.Time) time.Time {

	best := time.Time{}
	for _, cron := range schedule.Crons {
		new := cron.Next(currentTime)
		if best.IsZero() || new.Before(best) {
			best = new
		}
	}

	return best
}
