/*
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"
	v1 "k8s.io/api/core/v1"
	"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"
	informers "k8s.io/client-go/informers/core/v1"
	clientset "k8s.io/client-go/kubernetes/typed/core/v1"
	listers "k8s.io/client-go/listers/core/v1"
	"k8s.io/client-go/tools/cache"
)

type ServiceHandler func(string, *v1.Service) (*v1.Service, error)

type ServiceController interface {
	generic.ControllerMeta
	ServiceClient

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

	Cache() ServiceCache
}

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

type ServiceCache interface {
	Get(namespace, name string) (*v1.Service, error)
	List(namespace string, selector labels.Selector) ([]*v1.Service, error)

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

type ServiceIndexer func(obj *v1.Service) ([]string, error)

type serviceController struct {
	controllerManager *generic.ControllerManager
	clientGetter      clientset.ServicesGetter
	informer          informers.ServiceInformer
	gvk               schema.GroupVersionKind
}

func NewServiceController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.ServicesGetter, informer informers.ServiceInformer) ServiceController {
	return &serviceController{
		controllerManager: controllerManager,
		clientGetter:      clientGetter,
		informer:          informer,
		gvk:               gvk,
	}
}

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

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

func UpdateServiceDeepCopyOnChange(client ServiceClient, obj *v1.Service, handler func(obj *v1.Service) (*v1.Service, error)) (*v1.Service, 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 *serviceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) {
	c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler)
}

func (c *serviceController) 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 *serviceController) OnChange(ctx context.Context, name string, sync ServiceHandler) {
	c.AddGenericHandler(ctx, name, FromServiceHandlerToHandler(sync))
}

func (c *serviceController) OnRemove(ctx context.Context, name string, sync ServiceHandler) {
	removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromServiceHandlerToHandler(sync))
	c.AddGenericHandler(ctx, name, removeHandler)
}

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

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

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

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

func (c *serviceController) Cache() ServiceCache {
	return &serviceCache{
		lister:  c.informer.Lister(),
		indexer: c.informer.Informer().GetIndexer(),
	}
}

func (c *serviceController) Create(obj *v1.Service) (*v1.Service, error) {
	return c.clientGetter.Services(obj.Namespace).Create(obj)
}

func (c *serviceController) Update(obj *v1.Service) (*v1.Service, error) {
	return c.clientGetter.Services(obj.Namespace).Update(obj)
}

func (c *serviceController) UpdateStatus(obj *v1.Service) (*v1.Service, error) {
	return c.clientGetter.Services(obj.Namespace).UpdateStatus(obj)
}

func (c *serviceController) Delete(namespace, name string, options *metav1.DeleteOptions) error {
	return c.clientGetter.Services(namespace).Delete(name, options)
}

func (c *serviceController) Get(namespace, name string, options metav1.GetOptions) (*v1.Service, error) {
	return c.clientGetter.Services(namespace).Get(name, options)
}

func (c *serviceController) List(namespace string, opts metav1.ListOptions) (*v1.ServiceList, error) {
	return c.clientGetter.Services(namespace).List(opts)
}

func (c *serviceController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) {
	return c.clientGetter.Services(namespace).Watch(opts)
}

func (c *serviceController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Service, err error) {
	return c.clientGetter.Services(namespace).Patch(name, pt, data, subresources...)
}

type serviceCache struct {
	lister  listers.ServiceLister
	indexer cache.Indexer
}

func (c *serviceCache) Get(namespace, name string) (*v1.Service, error) {
	return c.lister.Services(namespace).Get(name)
}

func (c *serviceCache) List(namespace string, selector labels.Selector) ([]*v1.Service, error) {
	return c.lister.Services(namespace).List(selector)
}

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

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

type ServiceStatusHandler func(obj *v1.Service, status v1.ServiceStatus) (v1.ServiceStatus, error)

type ServiceGeneratingHandler func(obj *v1.Service, status v1.ServiceStatus) ([]runtime.Object, v1.ServiceStatus, error)

func RegisterServiceStatusHandler(ctx context.Context, controller ServiceController, condition condition.Cond, name string, handler ServiceStatusHandler) {
	statusHandler := &serviceStatusHandler{
		client:    controller,
		condition: condition,
		handler:   handler,
	}
	controller.AddGenericHandler(ctx, name, FromServiceHandlerToHandler(statusHandler.sync))
}

func RegisterServiceGeneratingHandler(ctx context.Context, controller ServiceController, apply apply.Apply,
	condition condition.Cond, name string, handler ServiceGeneratingHandler, opts *generic.GeneratingHandlerOptions) {
	statusHandler := &serviceGeneratingHandler{
		ServiceGeneratingHandler: handler,
		apply:                    apply,
		name:                     name,
		gvk:                      controller.GroupVersionKind(),
	}
	if opts != nil {
		statusHandler.opts = *opts
	}
	RegisterServiceStatusHandler(ctx, controller, condition, name, statusHandler.Handle)
}

type serviceStatusHandler struct {
	client    ServiceClient
	condition condition.Cond
	handler   ServiceStatusHandler
}

func (a *serviceStatusHandler) sync(key string, obj *v1.Service) (*v1.Service, 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 serviceGeneratingHandler struct {
	ServiceGeneratingHandler
	apply apply.Apply
	opts  generic.GeneratingHandlerOptions
	gvk   schema.GroupVersionKind
	name  string
}

func (a *serviceGeneratingHandler) Handle(obj *v1.Service, status v1.ServiceStatus) (v1.ServiceStatus, error) {
	objs, newStatus, err := a.ServiceGeneratingHandler(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...)
}
