package common

import (
	"context"
	"time"

	"k8s.io/apimachinery/pkg/types"

	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/controllers"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/controllers/appbox/task"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/deploy"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/helm"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/util"
)

type NodePinger struct {
	*task.BaseTask
}

func NewNodePinger(ctx *task.Context) *NodePinger {
	return &NodePinger{
		BaseTask: &task.BaseTask{Context: ctx},
	}
}

func (t *NodePinger) Name() string {
	return "NodePinger"
}

func (t *NodePinger) shouldSkip() bool {
	return t.InfraTmplConfig.NodePinger.ChartPath == "" ||
		t.APPBox.Annotations[v1alpha1.AnnotationKeyEnableNodePinger] != "true"
}

func (t *NodePinger) Create(ctx context.Context) deploy.Result {
	t.BeginAt = util.Pointer(time.Now())
	if t.shouldSkip() {
		return deploy.Done()
	}
	return deploy.ErrorOrDone(helm.Apply(ctx, t.Remote, t.InfraTmplConfig.NodePinger))
}

func (t *NodePinger) PostCreate(ctx context.Context) deploy.Result {
	if t.shouldSkip() {
		return deploy.Done()
	}
	return deploy.ErrorOrDone(controllers.EnsureDaemonSetReady(ctx, t.Remote, types.NamespacedName{
		Namespace: t.InfraTmplConfig.NodePinger.GetNamespace(),
		Name:      t.InfraTmplConfig.NodePinger.GetName(),
	}))
}
