package main

import (
	"fmt"
	"strconv"
	"testing"
	"time"
	"wdd.io/agent-common/assert"
	"wdd.io/agent-common/pusher"
	"wdd.io/agent-common/utils"
)

var CmiiDevNamespaceList = []string{
	"uavcloud-dev",
	"uavcloud-devflight",
	"uavcloud-devoperation",
}

func TestFindAppNotHealthyOrRestartCountGreaterThanN(t *testing.T) {

	deploymentRestartCountGreaterThanN := FindAppNotHealthyOrRestartCountGreaterThanN("devflight", 10)
	deploymentRestartCountGreaterThanN = FilterAllCmiiAppSoft(deploymentRestartCountGreaterThanN)

	for _, deploymentInterface := range deploymentRestartCountGreaterThanN {
		println()
		utils.BeautifulPrint(deploymentInterface)
		println()
	}

}

func TestFindDeploymentReplicasSmallerThanN(t *testing.T) {

	deploymentReplicasSmallerThanN := FindDeploymentReplicasSmallerThanN("devflight", 0)

	for _, deploymentInterface := range deploymentReplicasSmallerThanN {
		println()
		utils.BeautifulPrint(deploymentInterface)
		println()
	}

}

func TestFindCmiiMiddlewarePodInterface(t *testing.T) {
	middlewarePodInterface := FindCmiiMiddlewarePodInterface(integration)

	for _, middlePod := range middlewarePodInterface {
		println()
		utils.BeautifulPrint(middlePod)
		println()
	}
}

func TestRollBackCmiiDeploymentFromUpdateLog(t *testing.T) {
	updateLog := RollBackCmiiDeploymentFromUpdateLog("2024-01-10-14-37-07 uavcloud-devflight       cmii-uav-depotautoreturn                12345678            123sdsa45678")

	assert.Equal(t, updateLog, true, "roll back from update log failed !")
}

func TestRestartCmiiBackendDeployment(t *testing.T) {

	RestartCmiiBackendDeployment("dev")
}

func TestRestartCmiiFrontendDeployment(t *testing.T) {
	RestartCmiiFrontendDeployment("dev")
}

func TestFindDeploymentNotHealthy(t *testing.T) {

	for _, devNamespace := range CmiiDevNamespaceList {
		notHealthy := FindDeploymentNotHealthy(devNamespace)
		notHealthy = FilterAllCmiiAppSoft(notHealthy)
		for _, deploymentInterface := range notHealthy {
			utils.BeautifulPrint(deploymentInterface)
		}
	}
}

func TestFindAllNodeNotHealthy(t *testing.T) {
	start := time.Now()
	allNodeNotHealthy := FindAllNodeNotHealthy()
	elapsed := time.Since(start).Milliseconds()
	fmt.Printf("执行耗时： %d ms\n", elapsed)

	allNodeNotHealthy = FilterAllCmiiNodeSoft(allNodeNotHealthy)

	assert.Equal(t, len(allNodeNotHealthy), 0, "have unhealthy pod !")

	for _, nodeInterface := range allNodeNotHealthy {
		println()
		utils.BeautifulPrint(nodeInterface)
		println()
	}

}

func TestFindPodNotHealthy(t *testing.T) {

	podNotHealthy := FindPodNotHealthy("devfl")
	podNotHealthy = FilterAllCmiiPodSoft(podNotHealthy)

	for _, podInterface := range podNotHealthy {
		t.Logf("[%s] [%s]", podInterface.Name, podInterface.PodPhase)
	}
}

func TestFindPodNotHealthy_And_Delete(t *testing.T) {
	podNotHealthy := FindPodNotHealthy("devf")
	podNotHealthy = FilterAllCmiiPodSoft(podNotHealthy)

	for _, podInterface := range podNotHealthy {
		t.Logf("[%s] [%s]", podInterface.Name, podInterface.PodPhase)
		podDelete := DefaultCmiiOperator.PodDelete(podInterface.Namespace, podInterface.Name)

		assert.Equal(t, podDelete, true, "delete of ", podInterface.Namespace, podInterface.Name, " failed !")
	}

}

func TestFilterAllCmiiAppStrict(t *testing.T) {
	allInterface := DefaultCmiiOperator.DeploymentAllInterface("devflight")
	FilterAllCmiiAppStrict(allInterface)
}

func TestRestartDeploymentFromList(t *testing.T) {
	allInterface := DefaultCmiiOperator.DeploymentAllInterface("devflight")
	allInterface = FilterAllCmiiAppSoft(allInterface)

	RestartDeploymentFromList(allInterface)

}

func TestBackupAllCmiiDeploymentToMap(t *testing.T) {

	backendMap, frontendMap, srsMap := BackupAllCmiiDeploymentToMap(demo)

	utils.BeautifulPrint(backendMap)
	utils.BeautifulPrint(frontendMap)
	utils.BeautifulPrint(srsMap)
}

func TestBackupAllCmiiDeploymentToList(t *testing.T) {
	allCmiiImageList := BackupAllCmiiDeploymentToList(demo, true)

	utils.BeautifulPrint(allCmiiImageList)
}

// Update DEMO by Tag Update
func TestUpdateCmiiImageTagFromNameTagMap(t *testing.T) {

	cmii530BackendMap := map[string]string{
		"cmii-admin-data":               "5.7.0",
		"cmii-admin-gateway":            "5.7.0",
		"cmii-admin-user":               "5.7.0",
		"cmii-open-gateway":             "5.7.0",
		"cmii-suav-supervision":         "5.7.0",
		"cmii-uav-airspace":             "5.7.0",
		"cmii-uav-alarm":                "5.7.0",
		"cmii-uav-brain":                "5.7.0",
		"cmii-uav-cloud-live":           "5.7.0",
		"cmii-uav-cms":                  "5.7.0",
		"cmii-uav-data-post-process":    "5.7.0",
		"cmii-uav-developer":            "5.7.0",
		"cmii-uav-device":               "5.7.0",
		"cmii-uav-emergency":            "5.7.0",
		"cmii-uav-gateway":              "5.7.0",
		"cmii-uav-gis-server":           "5.7.0",
		"cmii-uav-industrial-portfolio": "5.7.0",
		"cmii-uav-integration":          "5.7.0",
		"cmii-uav-logger":               "5.7.0",
		"cmii-uav-material-warehouse":   "5.7.0",
		"cmii-uav-mission":              "5.7.0",
		"cmii-uav-mqtthandler":          "5.7.0",
		"cmii-uav-notice":               "5.7.0",
		"cmii-uav-oauth":                "5.7.0",
		"cmii-uav-process":              "5.7.0",
		"cmii-uav-surveillance":         "5.7.0",
		"cmii-uav-threedsimulation":     "5.7.0",
		"cmii-uav-tower":                "5.7.0",
		"cmii-uav-user":                 "5.7.0",
		"cmii-uav-waypoint":             "5.7.0",
		"cmii-uav-sense-adapter":        "5.7.0",
		"cmii-uav-multilink":            "5.7.0",
	}

	cmii530FrontendMap := map[string]string{
		"cmii-suav-platform-supervision":   "5.7.0",
		"cmii-suav-platform-supervisionh5": "5.7.0",
		"cmii-uav-platform":                "5.7.0",
		"cmii-uav-platform-ai-brain":       "5.7.0",
		"cmii-uav-platform-armypeople":     "5.7.0",
		//"cmii-uav-platform-base":             "5.7.0",
		"cmii-uav-platform-cms-portal": "5.7.0",
		//"cmii-uav-platform-detection":        "5.7.0",
		//"cmii-uav-platform-emergency-rescue": "5.7.0",
		//"cmii-uav-platform-logistics":        "5.7.0",
		"cmii-uav-platform-media": "5.7.0",
		//"cmii-uav-platform-multiterminal":    "5.7.0",
		"cmii-uav-platform-mws":        "5.7.0",
		"cmii-uav-platform-oms":        "5.7.0",
		"cmii-uav-platform-open":       "5.7.0",
		"cmii-uav-platform-securityh5": "5.7.0",
		//"cmii-uav-platform-seniclive":        "5.7.0",
		"cmii-uav-platform-share": "5.7.0",
		//"cmii-uav-platform-splice":           "5.7.0",
		//"cmii-uav-platform-threedsimulation": "5.7.0",
		//"cmii-uav-platform-visualization":    "5.7.0",
		//"cmii-uav-platform-security":         "4.1.6",
	}

	result := UpdateCmiiImageTagFromNameTagMap(demo, cmii530BackendMap)
	utils.BeautifulPrint(result)

	result = UpdateCmiiImageTagFromNameTagMap(demo, cmii530FrontendMap)
	utils.BeautifulPrint(result)

}

func TestScaleCmiiFrontendDeploymentToDesiredReplicas(t *testing.T) {
	ScaleCmiiFrontendDeploymentToDesiredReplicas(dev, 0)
}

func TestScaleCmiiBackendDeploymentToDesiredReplicas(t *testing.T) {
	ScaleCmiiBackendDeploymentToDesiredReplicas(dev, 0)
}

func TestBackupAllDeploymentFromEnv(t *testing.T) {

	BackupAllDeploymentFromEnvToFile(demo)

}

func TestBackUpAllCmiiAppImageNameFromEnv(t *testing.T) {

	BackUpAllCmiiAppImageNameFromEnv(demo)

}

func TestRestartCmiiDeployment(t *testing.T) {
	cmiiEnv := integration
	appName := "cmii-uav-platform"

	kill := DefaultCmiiOperator.DeploymentRestartByKill(cmiiEnv, appName)
	assert.Equal(t, kill, true, "have unhealthy pod !")

	check := DefaultCmiiOperator.DeploymentStatusCheck(cmiiEnv, appName, 180)
	assert.Equal(t, check, true, "DeploymentStatusCheck failed !")
}

func TestUpdateCmiiDeploymentImageTag(t *testing.T) {

	// 计算20:00的时间
	now := time.Now()

	targetTime := time.Date(now.Year(), now.Month(), now.Day(), 16, 55, 00, 0, now.Location())

	duration := time.Duration(0)

	if !now.After(targetTime) {
		// 计算到20:00的剩余时间
		duration = targetTime.Sub(now)
	} else {
		// 如果当前时间已经过了20:00，那么就跳到下一天
		//targetTime = targetTime.Add(24 * time.Hour)
	}

	fmt.Println(duration)

	// 等待到20:00
	time.Sleep(duration)

	cmiiEnv := demo
	//appName := "cmii-uav-platform"i
	//newTag := "5.4.0-032601"

	appNameTagMap := map[string]string{
		//"cmii-uav-platform-dispatchh5": "5.6.0-062401",
		//"cmii-uav-data-post-process": "5.6.0-062401",
		//"cmii-uav-industrial-portfolio": "5.6.0-071801",
		"cmii-uav-platform": "5.7.0",
		//"cmii-uav-brain":     "5.5.0",
		//"cmii-uav-platform": "5.6.0-071702",
		//"cmii-uas-lifecycle": "5.6.0-30403-071802",
	}

	for appName, newTag := range appNameTagMap {
		ok, oldImageTag, newImageTag := UpdateCmiiDeploymentImageTag(cmiiEnv, appName, newTag)

		if !ok {
			log.ErrorF("update image tag failed !")
			UpdateCmiiDeploymentImageTag(cmiiEnv, appName, oldImageTag)
		}
		utils.SplitLinePrint()

		check := DefaultCmiiOperator.DeploymentStatusCheck(cmiiEnv, appName, 300)
		assert.Equal(t, check, true, "deployment run failed!")
		if !check {
			UpdateCmiiDeploymentImageTag(cmiiEnv, appName, oldImageTag)
		}

		deploy := DefaultCmiiOperator.DeploymentOneInterface(cmiiEnv, appName)

		// push message
		message := pusher.CmiiUpdateMessage{
			Namespace:    cmiiEnv,
			AppName:      appName,
			FromTag:      oldImageTag,
			ToTag:        newImageTag,
			Replicas:     strconv.FormatInt(int64(deploy.Replicas), 10),
			DeployStatus: check,
		}
		message.SendMessage()

	}

}
