package tasks

import (
	"time"

	"github.com/giolekva/pcloud/core/installer"
	"github.com/giolekva/pcloud/core/installer/status"
)

func NewMonitorReleaseTasks(mon status.ResourceMonitor, rr installer.ReleaseResources) []Task {
	var t []Task
	for _, h := range rr.Helm {
		t = append(t, newMonitorHelm(mon, h))
	}
	return t
}

func NewMonitorRelease(mon status.ResourceMonitor, rr installer.ReleaseResources) Task {
	return newConcurrentParentTask("Monitor", true, NewMonitorReleaseTasks(mon, rr)...)
}

func newMonitorHelm(mon status.ResourceMonitor, h installer.Resource) Task {
	rType := h.Annotations["dodo.cloud/resource-type"]
	var name string
	switch rType {
	case "virtual-machine":
		name = h.Annotations["dodo.cloud/resource.virtual-machine.name"]
	case "mongodb":
		name = h.Annotations["dodo.cloud/resource.mongodb.name"]
	case "postgresql":
		name = h.Annotations["dodo.cloud/resource.postgresql.name"]
	case "volume":
		name = h.Annotations["dodo.cloud/resource.volume.name"]
	case "ingress":
		name = h.Annotations["dodo.cloud/resource.ingress.host"]
	case "service":
		name = h.Annotations["dodo.cloud/resource.service.name"]
	}
	t := newResourceLeafTask(h.Info, &ResourceId{rType, name}, func() error {
		ref := status.ResourceRef{
			Id:        h.Annotations["dodo.cloud/id"],
			Name:      h.Name,
			Namespace: h.Namespace,
		}
		for {
			if s, err := mon.Get(ref); err != nil {
				return err
			} else if status.IsStatusTerminal(s) {
				return nil
			} else {
				time.Sleep(5 * time.Second)
			}
		}
		return nil
	})
	return &t
}
