package bulk

import (
	"testing"
	"time"

	"code.justin.tv/d8a/buddy/lib/config"
	"github.com/stretchr/testify/require"
)

func checkRunTime(t *testing.T, startTime string, endTime string, crons ...string) {
	start, err := time.Parse(time.RFC3339, startTime)
	require.Nil(t, err)
	require.False(t, start.IsZero())

	expectedEnd, err := time.Parse(time.RFC3339, endTime)
	require.Nil(t, err)
	if len(crons) > 0 {
		require.False(t, expectedEnd.IsZero())
	} else {
		expectedEnd = time.Time{}
	}

	cfg := &config.ConfigFile{}

	for _, cron := range crons {
		cfg.BulkSchedule = append(cfg.BulkSchedule, config.BulkSchedule{
			CronSchedule: cron,
		})
	}

	schedule := NewSchedule(cfg.BulkSchedule)
	require.NotNil(t, schedule)

	realEnd := schedule.NextRun(start)
	require.Equal(t, expectedEnd, realEnd)
}

func TestNextRun(t *testing.T) {
	//6PM on monday january 23rd w/ full cron- run time is a minute later
	checkRunTime(t, "2017-01-23T18:00:00Z", "2017-01-23T18:01:00Z", "0 * 0-5,17-23 * * MON-THU *", "0 * 0-5,22-23 * * SUN,FRI-SAT *")
	//6PM on friday january 27th w/ weeknight cron - runtime is the following monday january 30th at 5pm
	checkRunTime(t, "2017-01-27T18:00:00Z", "2017-01-30T17:00:00Z", "0 * 17-23 * * MON-THU *")
	//9AM on wednesday january 25th w/ full cron - runtime is 5pm that evening
	checkRunTime(t, "2017-01-25T09:00:00Z", "2017-01-25T17:00:00Z", "0 * 0-5,17-23 * * MON-THU *", "0 * 0-5,22-23 * * SUN,FRI-SAT *")
	//7:01:52PM on monday january 23rd w/ full cron - run time is 8s later
	checkRunTime(t, "2017-01-23T19:01:52Z", "2017-01-23T19:02:00Z", "0 * 0-5,17-23 * * MON-THU *", "0 * 0-5,22-23 * * SUN,FRI-SAT *")
	//6PM on monday january 23rd w/ no cron - run time is zero time
	checkRunTime(t, "2017-01-23T18:00:00Z", "0001-01-01T00:00:00Z")
}
