package ticktock

import (
	"fmt"
	"time"

	"github.com/go-co-op/gocron/v2"
	"gitlink.org.cn/cloudream/common/pkgs/logger"
	"gitlink.org.cn/cloudream/jcs-pub/coordinator/internal/db"
)

type Job interface {
	Name() string
	Execute(t *TickTock)
}

type cronJob struct {
	cronJob gocron.Job
	job     Job
}

type TickTock struct {
	cfg  Config
	sch  gocron.Scheduler
	jobs map[string]cronJob
	db   *db.DB
}

func New(cfg Config, db *db.DB) *TickTock {
	sch, _ := gocron.NewScheduler()
	t := &TickTock{
		cfg:  cfg,
		sch:  sch,
		jobs: map[string]cronJob{},
		db:   db,
	}
	t.initJobs()
	return t
}

func (t *TickTock) Start() {
	t.sch.Start()
}

func (t *TickTock) Stop() {
	t.sch.Shutdown()
}

func (t *TickTock) RunNow(jobName string) {
	j, ok := t.jobs[jobName]
	if !ok {
		logger.Warnf("job %s not found", jobName)
		return
	}

	j.cronJob.RunNow()
}

func (t *TickTock) addJob(job Job, duration gocron.JobDefinition) {
	j, err := t.sch.NewJob(duration, gocron.NewTask(job.Execute, t))
	if err != nil {
		panic(fmt.Errorf("add job %s: %w", job.Name(), err))
	}

	t.jobs[job.Name()] = cronJob{
		cronJob: j,
		job:     job,
	}
}

func (t *TickTock) initJobs() {
	t.addJob(&CheckHubState{}, gocron.DurationJob(time.Minute*5))
}
