package v1

import (
	v1 "github.com/kubeflow/training-operator/pkg/apis/kubeflow.org/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/tools/cache"
)

// MXJobLister helps list MXJobs.
// All objects returned here must be treated as read-only.
type MXJobLister interface {
	// List lists all MXJobs in the indexer.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1.MXJob, err error)
	// MXJobs returns an object that can list and get MXJobs.
	MXJobs(namespace string) MXJobNamespaceLister
	MXJobListerExpansion
}

// mXJobLister implements the MXJobLister interface.
type mXJobLister struct {
	indexer cache.Indexer
}

// NewMXJobLister returns a new MXJobLister.
func NewMXJobLister(indexer cache.Indexer) MXJobLister {
	return &mXJobLister{indexer: indexer}
}

// List lists all MXJobs in the indexer.
func (s *mXJobLister) List(selector labels.Selector) (ret []*v1.MXJob, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*v1.MXJob))
	})
	return ret, err
}

// MXJobs returns an object that can list and get MXJobs.
func (s *mXJobLister) MXJobs(namespace string) MXJobNamespaceLister {
	return mXJobNamespaceLister{indexer: s.indexer, namespace: namespace}
}

// MXJobNamespaceLister helps list and get MXJobs.
// All objects returned here must be treated as read-only.
type MXJobNamespaceLister interface {
	// List lists all MXJobs in the indexer for a given namespace.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1.MXJob, err error)
	// Get retrieves the MXJob from the indexer for a given namespace and name.
	// Objects returned here must be treated as read-only.
	Get(name string) (*v1.MXJob, error)
	MXJobNamespaceListerExpansion
}

// mXJobNamespaceLister implements the MXJobNamespaceLister
// interface.
type mXJobNamespaceLister struct {
	indexer   cache.Indexer
	namespace string
}

// List lists all MXJobs in the indexer for a given namespace.
func (s mXJobNamespaceLister) List(selector labels.Selector) (ret []*v1.MXJob, err error) {
	err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
		ret = append(ret, m.(*v1.MXJob))
	})
	return ret, err
}

// Get retrieves the MXJob from the indexer for a given namespace and name.
func (s mXJobNamespaceLister) Get(name string) (*v1.MXJob, error) {
	obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(v1.Resource("mxjob"), name)
	}
	return obj.(*v1.MXJob), nil
}
