/*
Copyright 2017 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.
*/

package predicates

import (
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var (
	ResourceVersionChanged = ResourceVersionChangedPredicate{}
)

type Predicate interface {
	HandleUpdate(old, new interface{}) bool
	HandleDelete(obj interface{}) bool
	HandleCreate(obj interface{}) bool
}

type TrueMixin struct{}

func (TrueMixin) HandleUpdate(old, new interface{}) bool {
	return true
}

func (TrueMixin) HandleDelete(obj interface{}) bool {
	return true
}

func (TrueMixin) HandleCreate(obj interface{}) bool {
	return true
}

type FalseMixin struct{}

func (FalseMixin) HandleUpdate(old, new interface{}) bool {
	return false
}

func (FalseMixin) HandleDelete(obj interface{}) bool {
	return false
}

func (FalseMixin) HandleCreate(obj interface{}) bool {
	return false
}

type ResourceVersionChangedPredicate struct {
	TrueMixin
}

func (ResourceVersionChangedPredicate) HandleUpdate(old, new interface{}) bool {
	oldObject, ok := old.(metav1.Object)
	if !ok {
		fmt.Errorf("Cannot handle %T because old is not an Object: %v\n", oldObject, oldObject)
		return false
	}
	newObject, ok := new.(metav1.Object)
	if !ok {
		fmt.Errorf("Cannot handle %T because new is not an Object: %v\n", newObject, newObject)
		return false
	}

	if oldObject.GetResourceVersion() == newObject.GetResourceVersion() {
		// Periodic resync will send update events for all resources Deployments.
		return false
	}
	return true
}
