package charset_gbk

import (
	"net/url"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pingcap/log"
	"github.com/pingcap/test-infra/caselib/pkg/host"
	"github.com/pingcap/test-infra/sdk/resource"
	"go.uber.org/zap"

	. "github.com/pingcap/endless/pkg/matcher"
)

func TiupCreate(
	workloadNode resource.WorkloadNode,
	installVersion string,
	topo string,
) {
	cluster = host.NewTiUPCluster(workloadNode, "tiup-peer", topo, "debug").WithCMDTimeout(60 * time.Minute)
	workloadHost := host.NewWorkloadHost(workloadNode)
	cmd := "tiup mirror set 'http://staging.tiup-server.pingcap.net'"
	Try(workloadHost.Exec(cmd, 30000000000000))
	res, _, _, err := workloadNode.Exec(resource.WorkloadNodeExecOptions{Command: "tiup mirror show"}) // 直接用
	Expect(res).Should(ContainSubstring("staging"))
	must(cluster.Deploy(installVersion))
	must(cluster.Start())
	info, err := cluster.Display()
	log.Info("before upgrade", zap.String("current version:", info.ClusterMeta.ClusterVersion))
	must(err)
	dbURL = Try(cluster.ServiceURL(resource.DBAddr)).(*url.URL)
	log.Info("db info", zap.String("url", dbURL.String()), zap.String("ip:", dbURL.Hostname()), zap.String("port:", dbURL.Port()), zap.String("host:", dbURL.Hostname()))
}

func TiupDestroy() {
	Try(cluster.ServiceURL(resource.DBAddr))
	Try(cluster.Destroy())
}

func TiupUpdate(
	config string,
) {
	Try(cluster.Upgrade(targetVersion, "--wait-timeout 3600"))
	Try(cluster.UpdateConfig(resource.TiDBClusterUpdateConfigOptions{
		Target:  resource.TiDB,
		Config:  config,
		Timeout: 5 * time.Minute,
	}))
	info1 := Try(cluster.Display()).(host.TiUPClusterInfo)
	log.Info("after upgrade", zap.String("current version:", info1.ClusterMeta.ClusterVersion))
	if info1.ClusterMeta.ClusterVersion != targetVersion {
		Fail("upgrade fail")
	}
	Try(cluster.ServiceURL(resource.DBAddr))
}
