package ether

import (
	"github.com/coreos/etcd/clientv3"
	"github.com/ngaut/log"
	"golang.org/x/net/context"
)

// BackgroundJob is a interface to run background job.
type BackgroundJob interface {
	Name() string
	Run()
	Stop()
}

type backgroundWatchJob struct {
	client *clientv3.Client

	ctx    context.Context
	cancel context.CancelFunc

	prefix string
	name   string

	f func(event *clientv3.Event) error
}

func newBackgoundWatchJob(ctx context.Context, client *clientv3.Client, name, prefix string, f func(event *clientv3.Event) error) *backgroundWatchJob {
	ctx, cancel := context.WithCancel(ctx)
	return &backgroundWatchJob{
		client: client,

		prefix: prefix,
		name:   name,
		f:      f,

		ctx:    ctx,
		cancel: cancel,
	}
}

func (b *backgroundWatchJob) Name() string {
	return b.name
}

func (b *backgroundWatchJob) Stop() {
	b.cancel()
}

func (b *backgroundWatchJob) Run() {
	for {
		select {
		case <-b.ctx.Done():
			log.Infof("[ether] context cancelled")
			return
		default:
		}
		if err := watch(b.ctx, b.client, b.prefix, b.f); err != nil {
			log.Errorf("[ether] watch %v error %v", b.name, err)
		}
	}
}
