package utils

import (
	"errors"

	xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
	corev1 "k8s.io/api/core/v1"
)

// TODO(shenjun): this two can merge into one func to check ready and sync

func IsReady(conditions []xpv1.Condition) bool {
	if len(conditions) == 0 {
		return false
	}
	for _, c := range conditions {
		if c.Type == xpv1.TypeReady && c.Status == corev1.ConditionTrue {
			return true
		}
	}
	return false
}

// we only consider not ready and not sync as failed
func IsSyncFailed(conditions []xpv1.Condition) (bool, error) {
	if len(conditions) == 0 {
		return false, nil
	}
	for _, c := range conditions {
		if c.Type == xpv1.TypeSynced && c.Status == corev1.ConditionFalse && c.Reason == xpv1.ReasonReconcileError {
			return true, errors.New(c.Message)
		}
	}
	return false, nil
}

// GetConditions returns the ready and synced conditions of crossplane resources.
func GetConditions(conditions []xpv1.Condition) (ready, synced bool) {
	for _, c := range conditions {
		switch c.Type {
		case xpv1.TypeReady:
			ready = c.Status == corev1.ConditionTrue
		case xpv1.TypeSynced:
			synced = c.Status == corev1.ConditionTrue
		}
	}

	return ready, synced
}
