package ccb_application_router

import (
	"fmt"
	"strings"
	"time"

	. "github.com/onsi/gomega"

	"github.com/pingcap/log"

	. "github.com/pingcap/endless/pkg/matcher"
	"github.com/pingcap/endless/pkg/workloadnode/tiup"
)

func ReDeployCluster(tiupCluster *tiup.TiUPCluster, instancesCount InstancesCount, APIVersion int, ClusterVersion string) {
	tiupCluster.Destroy("--retain-node-data", "tiup-0.tiup-peer")
	PDTopo := GetRawKVClusterPDTopo(instancesCount.PDCount)
	TiDBTopo := GetRawKVClusterTiDBTopo(instancesCount.TiDBCount, ClusterVersion, APIVersion)
	TiKVTopo := GetRawKVClusterTiKVTopo(instancesCount.TiKVCount, instancesCount.ZoneCount)
	tiupTopo := fmt.Sprintf(TiupTopoTemplate, DeployUser, DeployDir, DataDir, instancesCount.ReplicaCount, GetStorageAPIVersion(APIVersion, ClusterVersion), PDTopo, TiDBTopo, TiKVTopo)
	tiupCluster.Topology = tiupTopo
	err := tiupCluster.Deploy(ClusterVersion)
	if err != nil {
		if strings.Contains(err.Error(), "Cluster name 'rawkv' is duplicated") {
			log.Info("Cluster name 'rawkv' has already deployed")
		} else {
			Expect(err).Should(BeNil())
		}
	} else {
		Try(tiupCluster.Start())
	}
}

func UpgradeClusterToV610(stageDesc string, tiupCluster *tiup.TiUPCluster, UpgradeVersion string) TestCaseStageInfo {
	stage := TestCaseStageInfo{
		Description: stageDesc,
		Start:       time.Now(),
	}
	err := tiupCluster.Upgrade(UpgradeVersion)
	Expect(err).Should(BeNil())
	stage.End = time.Now()
	return stage
}

func CleanCluster(stageDesc string, tiupCluster *tiup.TiUPCluster) TestCaseStageInfo {
	stage := TestCaseStageInfo{
		Description: stageDesc,
		Start:       time.Now(),
	}
	cmd := "tiup cluster clean rawkv --all --ignore-node tiup-0.peer"
	err := tiupCluster.ControlNodeHost.Run(cmd, tiupCluster.CMDTimeout)
	Expect(err).Should(BeNil())
	stage.End = time.Now()
	return stage
}
