/*
Copyright 2022.

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 controllers

import (
	"context"
	"fmt"
	"github.com/tidbcloud/operationlet/diagnostic"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"

	cloudv1 "github.com/tidbcloud/operationlet/api/v1"
)

// DiagnosticCollectorJobReconciler reconciles a DiagnosticCollectorJob object
type DiagnosticCollectorJobReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

//+kubebuilder:rbac:groups=cloud.cloud.pingcap.com,resources=diagnosticcollectorjobs,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=cloud.cloud.pingcap.com,resources=diagnosticcollectorjobs/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=cloud.cloud.pingcap.com,resources=diagnosticcollectorjobs/finalizers,verbs=update

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the DiagnosticCollectorJob object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.8.3/pkg/reconcile
func (r *DiagnosticCollectorJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	var err error
	logger := log.FromContext(ctx)
	logger.Info("Reconcile DiagnosticCollectorJob")
	// your logic here
	job := &cloudv1.DiagnosticCollectorJob{}
	if err := r.Get(ctx, req.NamespacedName, job); err != nil {
		return ctrl.Result{}, err
	}

	if job.Status.Phase == "" {
		if err := r.transToStatus(ctx, job, cloudv1.JobPhaseWaiting); err != nil {
			return ctrl.Result{}, err
		}
	}
	logger.Info("Watch diagnostic job!.",
		"type", job.Spec.Type,
		"cluster_id", job.Spec.ClusterId,
		"tenant_id", job.Spec.TenantId)

	switch job.Status.Phase {
	case cloudv1.JobPhaseWaiting, cloudv1.JobPhaseRunning:
		err = r.observeJob(ctx, job)
	case cloudv1.JobPhasePending:
		err = r.runJob(ctx, job)
	}
	return ctrl.Result{Requeue: true}, err
}

// SetupWithManager sets up the controller with the Manager.
func (r *DiagnosticCollectorJobReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&cloudv1.DiagnosticCollectorJob{}).
		Complete(r)
}

func (r *DiagnosticCollectorJobReconciler) runJob(ctx context.Context, job *cloudv1.DiagnosticCollectorJob) error {
	var err error
	var result string
	logger := log.FromContext(ctx)
	defer func() {
		if err != nil {
			logger.Error(err, "run job failed", "jobName", job.Name, "jobType", job.Spec.Type)
			if err = r.transToStatus(ctx, job, cloudv1.JobPhaseFailed); err != nil {
				logger.Error(err, "update job status failed", "jobName", job.Name, "jobType", job.Spec.Type)
			}
		}
	}()
	logger.Info("command job run", "jobName", job.Name,
		"jobType", job.Spec.Type,
		"clusterId", job.Spec.ClusterId,
		"tenantId", job.Spec.TenantId)
	switch job.Spec.Type {
	case cloudv1.GetConfig:
		result, err = r.GetConfig(ctx, job)
	}
	if err != nil {
		return err
	}
	job.Status.Result = result
	if err := r.Status().Update(ctx, job); err != nil {
		return err
	}
	return r.transToStatus(ctx, job, cloudv1.JobPhaseSuccess)
}

func (r *DiagnosticCollectorJobReconciler) observeJob(ctx context.Context, job *cloudv1.DiagnosticCollectorJob) error {
	var err error
	logger := log.FromContext(ctx)
	switch job.Status.Phase {
	case cloudv1.JobPhaseWaiting:
		logger.Info("job pending and need approve.", "job_name", job.Name)
	case cloudv1.JobPhaseRunning:
		if job.Status.Result != "" {
			job.Status.Phase = cloudv1.JobPhaseSuccess
			err = r.Status().Update(ctx, job)
		}
	}
	return err
}

func (r *DiagnosticCollectorJobReconciler) transToStatus(ctx context.Context, job *cloudv1.DiagnosticCollectorJob, newStatus cloudv1.CommandJobPhase) error {
	var err error
	logger := log.FromContext(ctx)
	if job.Status.Phase != newStatus {
		logger.Info("command job update status", "jobName", job.Name,
			"oldStatus", string(job.Status.Phase),
			"newStatus", string(newStatus))
		job.Status.Phase = newStatus
		err = r.Status().Update(ctx, job)
	}
	return err
}

func (r *DiagnosticCollectorJobReconciler) GetConfig(ctx context.Context, job *cloudv1.DiagnosticCollectorJob) (string, error) {
	logger := log.FromContext(ctx)
	pods := &corev1.PodList{}
	selector, _ := labels.Parse(fmt.Sprintf("app.kubernetes.io/component=%s", PD))
	option := &client.ListOptions{
		LabelSelector: selector,
		Namespace:     NamespacePrefix + job.Spec.ClusterId,
		Limit:         1,
	}
	if err := r.Client.List(context.TODO(), pods, option); err != nil {
		return "", err
	}
	if len(pods.Items) == 0 {
		logger.Error(fmt.Errorf("no pd pod found"), "", "clusterId", job.Spec.ClusterId)
		return "", fmt.Errorf("GetConfig: no pd pod found")
	}
	pod := pods.Items[0]
	labels := pod.GetLabels()
	if instance, ok := labels["app.kubernetes.io/instance"]; ok {
		pdUrl := fmt.Sprintf("https://%s.%s-%s-peer.%s:%s", pod.Name, instance, PD, pod.Namespace, PD_PORT)
		return diagnostic.GetConfig(pdUrl)
	}
	return "", fmt.Errorf("GetConfig: no instance label found")
}
