/*
Copyright The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Code generated by main. DO NOT EDIT.

package v1

import (
	"context"
	"time"

	"github.com/rancher/wrangler/pkg/apply"
	"github.com/rancher/wrangler/pkg/condition"
	"github.com/rancher/wrangler/pkg/generic"
	"k8s.io/apimachinery/pkg/api/equality"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/tools/cache"
	v1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
	clientset "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/typed/apiregistration/v1"
	informers "k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1"
	listers "k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1"
)

type APIServiceHandler func(string, *v1.APIService) (*v1.APIService, error)

type APIServiceController interface {
	generic.ControllerMeta
	APIServiceClient

	OnChange(ctx context.Context, name string, sync APIServiceHandler)
	OnRemove(ctx context.Context, name string, sync APIServiceHandler)
	Enqueue(name string)
	EnqueueAfter(name string, duration time.Duration)

	Cache() APIServiceCache
}

type APIServiceClient interface {
	Create(*v1.APIService) (*v1.APIService, error)
	Update(*v1.APIService) (*v1.APIService, error)
	UpdateStatus(*v1.APIService) (*v1.APIService, error)
	Delete(name string, options *metav1.DeleteOptions) error
	Get(name string, options metav1.GetOptions) (*v1.APIService, error)
	List(opts metav1.ListOptions) (*v1.APIServiceList, error)
	Watch(opts metav1.ListOptions) (watch.Interface, error)
	Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.APIService, err error)
}

type APIServiceCache interface {
	Get(name string) (*v1.APIService, error)
	List(selector labels.Selector) ([]*v1.APIService, error)

	AddIndexer(indexName string, indexer APIServiceIndexer)
	GetByIndex(indexName, key string) ([]*v1.APIService, error)
}

type APIServiceIndexer func(obj *v1.APIService) ([]string, error)

type aPIServiceController struct {
	controllerManager *generic.ControllerManager
	clientGetter      clientset.APIServicesGetter
	informer          informers.APIServiceInformer
	gvk               schema.GroupVersionKind
}

func NewAPIServiceController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.APIServicesGetter, informer informers.APIServiceInformer) APIServiceController {
	return &aPIServiceController{
		controllerManager: controllerManager,
		clientGetter:      clientGetter,
		informer:          informer,
		gvk:               gvk,
	}
}

func FromAPIServiceHandlerToHandler(sync APIServiceHandler) generic.Handler {
	return func(key string, obj runtime.Object) (ret runtime.Object, err error) {
		var v *v1.APIService
		if obj == nil {
			v, err = sync(key, nil)
		} else {
			v, err = sync(key, obj.(*v1.APIService))
		}
		if v == nil {
			return nil, err
		}
		return v, err
	}
}

func (c *aPIServiceController) Updater() generic.Updater {
	return func(obj runtime.Object) (runtime.Object, error) {
		newObj, err := c.Update(obj.(*v1.APIService))
		if newObj == nil {
			return nil, err
		}
		return newObj, err
	}
}

func UpdateAPIServiceDeepCopyOnChange(client APIServiceClient, obj *v1.APIService, handler func(obj *v1.APIService) (*v1.APIService, error)) (*v1.APIService, error) {
	if obj == nil {
		return obj, nil
	}

	copyObj := obj.DeepCopy()
	newObj, err := handler(copyObj)
	if newObj != nil {
		copyObj = newObj
	}
	if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) {
		return client.Update(copyObj)
	}

	return copyObj, err
}

func (c *aPIServiceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) {
	c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler)
}

func (c *aPIServiceController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) {
	removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler)
	c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler)
}

func (c *aPIServiceController) OnChange(ctx context.Context, name string, sync APIServiceHandler) {
	c.AddGenericHandler(ctx, name, FromAPIServiceHandlerToHandler(sync))
}

func (c *aPIServiceController) OnRemove(ctx context.Context, name string, sync APIServiceHandler) {
	removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromAPIServiceHandlerToHandler(sync))
	c.AddGenericHandler(ctx, name, removeHandler)
}

func (c *aPIServiceController) Enqueue(name string) {
	c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), "", name)
}

func (c *aPIServiceController) EnqueueAfter(name string, duration time.Duration) {
	c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), "", name, duration)
}

func (c *aPIServiceController) Informer() cache.SharedIndexInformer {
	return c.informer.Informer()
}

func (c *aPIServiceController) GroupVersionKind() schema.GroupVersionKind {
	return c.gvk
}

func (c *aPIServiceController) Cache() APIServiceCache {
	return &aPIServiceCache{
		lister:  c.informer.Lister(),
		indexer: c.informer.Informer().GetIndexer(),
	}
}

func (c *aPIServiceController) Create(obj *v1.APIService) (*v1.APIService, error) {
	return c.clientGetter.APIServices().Create(obj)
}

func (c *aPIServiceController) Update(obj *v1.APIService) (*v1.APIService, error) {
	return c.clientGetter.APIServices().Update(obj)
}

func (c *aPIServiceController) UpdateStatus(obj *v1.APIService) (*v1.APIService, error) {
	return c.clientGetter.APIServices().UpdateStatus(obj)
}

func (c *aPIServiceController) Delete(name string, options *metav1.DeleteOptions) error {
	return c.clientGetter.APIServices().Delete(name, options)
}

func (c *aPIServiceController) Get(name string, options metav1.GetOptions) (*v1.APIService, error) {
	return c.clientGetter.APIServices().Get(name, options)
}

func (c *aPIServiceController) List(opts metav1.ListOptions) (*v1.APIServiceList, error) {
	return c.clientGetter.APIServices().List(opts)
}

func (c *aPIServiceController) Watch(opts metav1.ListOptions) (watch.Interface, error) {
	return c.clientGetter.APIServices().Watch(opts)
}

func (c *aPIServiceController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.APIService, err error) {
	return c.clientGetter.APIServices().Patch(name, pt, data, subresources...)
}

type aPIServiceCache struct {
	lister  listers.APIServiceLister
	indexer cache.Indexer
}

func (c *aPIServiceCache) Get(name string) (*v1.APIService, error) {
	return c.lister.Get(name)
}

func (c *aPIServiceCache) List(selector labels.Selector) ([]*v1.APIService, error) {
	return c.lister.List(selector)
}

func (c *aPIServiceCache) AddIndexer(indexName string, indexer APIServiceIndexer) {
	utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{
		indexName: func(obj interface{}) (strings []string, e error) {
			return indexer(obj.(*v1.APIService))
		},
	}))
}

func (c *aPIServiceCache) GetByIndex(indexName, key string) (result []*v1.APIService, err error) {
	objs, err := c.indexer.ByIndex(indexName, key)
	if err != nil {
		return nil, err
	}
	result = make([]*v1.APIService, 0, len(objs))
	for _, obj := range objs {
		result = append(result, obj.(*v1.APIService))
	}
	return result, nil
}

type APIServiceStatusHandler func(obj *v1.APIService, status v1.APIServiceStatus) (v1.APIServiceStatus, error)

type APIServiceGeneratingHandler func(obj *v1.APIService, status v1.APIServiceStatus) ([]runtime.Object, v1.APIServiceStatus, error)

func RegisterAPIServiceStatusHandler(ctx context.Context, controller APIServiceController, condition condition.Cond, name string, handler APIServiceStatusHandler) {
	statusHandler := &aPIServiceStatusHandler{
		client:    controller,
		condition: condition,
		handler:   handler,
	}
	controller.AddGenericHandler(ctx, name, FromAPIServiceHandlerToHandler(statusHandler.sync))
}

func RegisterAPIServiceGeneratingHandler(ctx context.Context, controller APIServiceController, apply apply.Apply,
	condition condition.Cond, name string, handler APIServiceGeneratingHandler, opts *generic.GeneratingHandlerOptions) {
	statusHandler := &aPIServiceGeneratingHandler{
		APIServiceGeneratingHandler: handler,
		apply:                       apply,
		name:                        name,
		gvk:                         controller.GroupVersionKind(),
	}
	if opts != nil {
		statusHandler.opts = *opts
	}
	RegisterAPIServiceStatusHandler(ctx, controller, condition, name, statusHandler.Handle)
}

type aPIServiceStatusHandler struct {
	client    APIServiceClient
	condition condition.Cond
	handler   APIServiceStatusHandler
}

func (a *aPIServiceStatusHandler) sync(key string, obj *v1.APIService) (*v1.APIService, error) {
	if obj == nil {
		return obj, nil
	}

	origStatus := obj.Status
	obj = obj.DeepCopy()
	newStatus, err := a.handler(obj, obj.Status)
	if err != nil {
		// Revert to old status on error
		newStatus = *origStatus.DeepCopy()
	}

	obj.Status = newStatus
	if a.condition != "" {
		if errors.IsConflict(err) {
			a.condition.SetError(obj, "", nil)
		} else {
			a.condition.SetError(obj, "", err)
		}
	}
	if !equality.Semantic.DeepEqual(origStatus, obj.Status) {
		var newErr error
		obj, newErr = a.client.UpdateStatus(obj)
		if err == nil {
			err = newErr
		}
	}
	return obj, err
}

type aPIServiceGeneratingHandler struct {
	APIServiceGeneratingHandler
	apply apply.Apply
	opts  generic.GeneratingHandlerOptions
	gvk   schema.GroupVersionKind
	name  string
}

func (a *aPIServiceGeneratingHandler) Handle(obj *v1.APIService, status v1.APIServiceStatus) (v1.APIServiceStatus, error) {
	objs, newStatus, err := a.APIServiceGeneratingHandler(obj, status)
	if err != nil {
		return newStatus, err
	}

	apply := a.apply

	if !a.opts.DynamicLookup {
		apply = apply.WithStrictCaching()
	}

	if !a.opts.AllowCrossNamespace && !a.opts.AllowClusterScoped {
		apply = apply.WithSetOwnerReference(true, false).
			WithDefaultNamespace(obj.GetNamespace()).
			WithListerNamespace(obj.GetNamespace())
	}

	if !a.opts.AllowClusterScoped {
		apply = apply.WithRestrictClusterScoped()
	}

	return newStatus, apply.
		WithOwner(obj).
		WithSetID(a.name).
		ApplyObjects(objs...)
}
