/*

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 notification

import (
	"context"
	controller2 "github.com/argoproj-labs/argo-kube-notifier/notification/controller"
	argoprojv1alpha1 "github.com/argoproj-labs/argo-kube-notifier/pkg/apis/argoproj/v1alpha1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller"
	"sigs.k8s.io/controller-runtime/pkg/handler"
	"sigs.k8s.io/controller-runtime/pkg/manager"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
	logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
	"sigs.k8s.io/controller-runtime/pkg/source"
)

var log = logf.Log.WithName("controller")

/**
* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller
* business logic.  Delete these comments after modifying this file.*
 */

// Add creates a new Notification Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func Add(mgr manager.Manager) error {
	return add(mgr, newReconciler(mgr))
}

// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
	nnc := controller2.CreateNewNotificationController("")
	go nnc.Starworker(make(chan struct{}))
	return &ReconcileNotification{Client: mgr.GetClient(), scheme: mgr.GetScheme(), newController: nnc}
}

// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler) error {
	// Create a new controller
	c, err := controller.New("notification-controller", mgr, controller.Options{Reconciler: r})
	if err != nil {
		return err
	}

	// Watch for changes to Notification
	err = c.Watch(&source.Kind{Type: &argoprojv1alpha1.Notification{}}, &handler.EnqueueRequestForObject{})
	if err != nil {
		return err
	}
	//
	//// TODO(user): Modify this to be the types you create
	//// Uncomment watch a Deployment created by Notification - change this for objects you create
	//err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{
	//	IsController: true,
	//	OwnerType:    &argoprojv1alpha1.Notification{},
	//})
	//if err != nil {
	//	return err
	//}

	return nil
}

var _ reconcile.Reconciler = &ReconcileNotification{}

// ReconcileNotification reconciles a Notification object
type ReconcileNotification struct {
	client.Client
	scheme        *runtime.Scheme
	newController controller2.NewNotificationController
}

// Reconcile reads that state of the cluster for a Notification object and makes changes based on the state read
// and what is in the Notification.Spec
// TODO(user): Modify this Reconcile function to implement your Controller logic.  The scaffolding writes
// a Deployment as an example
// Automatically generate RBAC rules to allow the Controller to read and write Deployments
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=argoproj.io,resources=notifications,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=argoproj.io,resources=notifications/status,verbs=get;update;patch
func (r *ReconcileNotification) Reconcile(request reconcile.Request) (reconcile.Result, error) {
	// Fetch the Notification instance
	instance := &argoprojv1alpha1.Notification{}
	err := r.Get(context.TODO(), request.NamespacedName, instance)
	if err != nil {
		if errors.IsNotFound(err) {
			r.newController.UnRegisterNotification(instance)
			return reconcile.Result{}, nil
		}
		// Error reading the object - requeue the request.
		return reconcile.Result{}, err
	}

	r.newController.RegisterNotification(instance)

	//// TODO(user): Change this to be the object type created by your controller
	//// Define the desired Deployment object
	//deploy := &appsv1.Deployment{
	//	ObjectMeta: metav1.ObjectMeta{
	//		Name:      instance.Name + "-deployment",
	//		Namespace: instance.Namespace,
	//	},
	//	Spec: appsv1.DeploymentSpec{
	//		Selector: &metav1.LabelSelector{
	//			MatchLabels: map[string]string{"deployment": instance.Name + "-deployment"},
	//		},
	//		Template: corev1.PodTemplateSpec{
	//			ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"deployment": instance.Name + "-deployment"}},
	//			Spec: corev1.PodSpec{
	//				Containers: []corev1.Container{
	//					{
	//						Name:  "nginx",
	//						Image: "nginx",
	//					},
	//				},
	//			},
	//		},
	//	},
	//}
	//if err := controllerutil.SetControllerReference(instance, deploy, r.scheme); err != nil {
	//	return reconcile.Result{}, err
	//}
	//
	//// TODO(user): Change this for the object type created by your controller
	//// Check if the Deployment already exists
	//found := &appsv1.Deployment{}
	//err = r.Get(context.TODO(), types.NamespacedName{Name: deploy.Name, Namespace: deploy.Namespace}, found)
	//if err != nil && errors.IsNotFound(err) {
	//	log.Info("Creating Deployment", "namespace", deploy.Namespace, "name", deploy.Name)
	//	err = r.Create(context.TODO(), deploy)
	//	return reconcile.Result{}, err
	//} else if err != nil {
	//	return reconcile.Result{}, err
	//}
	//
	//// TODO(user): Change this for the object type created by your controller
	//// Update the found object and write the result back if there are any changes
	//if !reflect.DeepEqual(deploy.Spec, found.Spec) {
	//	found.Spec = deploy.Spec
	//	log.Info("Updating Deployment", "namespace", deploy.Namespace, "name", deploy.Name)
	//	err = r.Update(context.TODO(), found)
	//	if err != nil {
	//		return reconcile.Result{}, err
	//	}
	//}
	return reconcile.Result{}, nil
}
