//go:build !runOnTask

package jobqueue

import (
	"github.com/robfig/cron/v3"
	"github.com/stretchr/testify/assert"
	"go.uber.org/zap"

	"strings"
	"testing"
	"time"
)

// TestRoundTrip tests the round trip of jobs from yaml to the manager and back to yaml
// This test runs forever and must be stopped manually
// Use the following command to run this test:
// go test -timeout 6h -run TestRoundTrip -v
func TestRoundTrip(t *testing.T) {

	// define test data with jobs in yaml format
	testData := []byte(`
- id: job1
  priority: 1
  timeout: 1s
  maxRetries: 3
  retryDelay: 1s
  runnable:
   type: shell
   data:
     script: echo "~1~ $(date "+%M:%S")" >> /tmp/job1.log
  scheduler:
   type: cron
   spec: "*/10 * * * * *"
- id: job2
  priority: 1
  timeout: 1s
  maxRetries: 3
  retryDelay: 1s
  runnable:
   type: shell
   data:
     script: echo "~~~~2~ $(date "+%M:%S")" >> /tmp/job1.log
  scheduler:
   type: cron
   spec: "*/5 * * * * *"
- id: job3
  priority: 1
  timeout: 1s
  maxRetries: 3
  retryDelay: 1s
  runnable:
    type: shell
    data:
      script: echo "~~~~~~3~ $(date "+%M:%S")" >> /tmp/job1.log
  scheduler:
    type: interval
    interval: 20s
`)

	var err error

	cronInstance := cron.New(cron.WithSeconds())
	cronInstance.Start()

	zapLogger, _ := zap.NewDevelopment()
	_ = zapLogger

	manager := NewManager()
	manager.SetLogger(&ZapAdapter{logger: zapLogger})

	manager.SetCronInstance(cronInstance)
	worker := NewLocalWorker(10)
	worker.SetManager(manager)
	err = manager.AddWorker(worker)

	assert.Nil(t, err)

	err = manager.Start()
	assert.Nil(t, err)

	reader := strings.NewReader(string(testData))

	err = ImportJobsAndSchedule(reader, "yaml", manager)
	assert.Nil(t, err)

	for {
		time.Sleep(1 * time.Second)
	}

}