// Copyright 2018 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package tepcluster

import (
	"github.com/pingcap/tidb-enterprise/installer/tep-operator/pkg/apis/pingcap.com/v1alpha1"
	"github.com/pingcap/tidb-enterprise/installer/tep-operator/provisioner"
	apiequality "k8s.io/apimachinery/pkg/api/equality"
	errorutils "k8s.io/apimachinery/pkg/util/errors"
	"k8s.io/client-go/tools/record"
)

// ControlInterface implements the control logic for updating TepClusters
// It is implemented as an interface to allow for extensions that provide different semantics.
// Currently, there is only one implementation.
type ControlInterface interface {
	// UpdateTepCluster implements the control logic for Tepclusters creation, update, and deletion
	UpdateTepCluster(*v1alpha1.TepCluster) error
}

// NewDefaultTepClusterControl returns a new instance of the default implementation TepClusterControlInterface that
// implements the documented semantics for TepClusters.
func NewDefaultTepClusterControl(
	ansible provisioner.Provisioner,
	statusUpdater TepClusterStatusControlInterface,
	recorder record.EventRecorder) ControlInterface {
	return &defaultTepClusterControl{
		ansible,
		statusUpdater,
		recorder,
	}
}

type defaultTepClusterControl struct {
	ansible       provisioner.Provisioner
	statusUpdater TepClusterStatusControlInterface
	recorder      record.EventRecorder
}

// UpdateTepCluster executes the core logic loop for a tepcluster.
func (tcc *defaultTepClusterControl) UpdateTepCluster(tc *v1alpha1.TepCluster) error {
	// perform the main update function and get the status
	oldStatus := tc.Status.DeepCopy()
	var errs []error

	err := tcc.realUpdateTepCluster(tc)
	if err != nil {
		errs = append(errs, err)
	}

	if !apiequality.Semantic.DeepEqual(&tc.Status, oldStatus) {
		err = tcc.statusUpdater.UpdateTepClusterStatus(tc.DeepCopy(), &tc.Status)
		if err != nil {
			errs = append(errs, err)
		}
	}

	return errorutils.NewAggregate(errs)
}

func (tcc *defaultTepClusterControl) realUpdateTepCluster(tc *v1alpha1.TepCluster) error {
	if tc.Spec.Launch == v1alpha1.TepClusterStop {
		// stop the operation of tep cluster
		return tcc.ansible.Cancel()
	}
	// start to preparing for tep cluster
	err := tcc.ansible.Prepare(tc)
	if err != nil {
		return err
	}
	// start to provisioning tep cluster
	err = tcc.ansible.Provision(tc)
	if err != nil {
		return err
	}
	//TODO: shouldn't overwrite tc's status when tep operator restart
	ps := tcc.ansible.GetProvisionerStatus()
	tc.Status.Phase = ps.Phase
	return nil
}
