package main

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

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(config.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(config.Demo)

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

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

	utils.BeautifulPrint(allCmiiImageList)
}

// 直接更新DEMO的Tag，实现DEMO更新
func TestUpdateCmiiImageTagFromNameTagMap(t *testing.T) {

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

	frontendMap := map[string]string{
		"cmii-suav-platform-supervision":   "6.2.0-demo",
		"cmii-suav-platform-supervisionh5": "6.2.0-demo",
		"cmii-uav-platform":                "6.2.0-demo",
		"cmii-uav-platform-media":          "6.2.0-demo",
		"cmii-uav-platform-ai-brain":       "6.2.0-demo",
		"cmii-uav-platform-cms-portal":     "6.2.0-demo",
		"cmii-uav-platform-armypeople":     "6.2.0-demo",
		"cmii-uav-platform-mws":            "6.2.0-demo",
		"cmii-uav-platform-oms":            "6.2.0-demo",
		"cmii-uav-platform-open":           "6.2.0-demo",
		"cmii-uav-platform-securityh5":     "6.2.0-demo",
		"cmii-uav-platform-share":          "6.2.0-demo",
		"cmii-uav-platform-uasms":          "6.2.0-demo",
		"cmii-uav-platform-uas":            "6.2.0-demo",
		//"cmii-uav-platform-base":             "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-multiterminal":    "5.7.0",
		//"cmii-uav-platform-seniclive":        "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(config.Demo, backendMap)
	utils.BeautifulPrint(result)

	result = UpdateCmiiImageTagFromNameTagMap(config.Demo, frontendMap)
	utils.BeautifulPrint(result)

}

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

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

func TestBackupAllDeploymentFromEnv(t *testing.T) {

	BackupAllDeploymentFromEnvToFile(config.Demo)

}

func TestBackUpAllCmiiAppImageNameFroEnv(t *testing.T) {

	BackUpAllCmiiAppImageNameFromEnv(config.Demo)

}

func TestRestartCmiiDeployment(t *testing.T) {
	cmiiEnv := config.Demo
	appNameList := []string{
		"cmii-uav-industrial-portfolio",
	}

	for _, appName := range appNameList {
		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 !")
	}

	appName := "cmii-uav-notice"

	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(), 17, 23, 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 := config.Demo

	appNameTagMap := map[string]string{
		//"cmii-app-release": "6.1.0-122001",
		//"cmii-uav-platform-oms": "6.2.0-012201",
		//"cmii-uas-lifecycle":  "6.2.0-012301",
		"cmii-uav-advanced5g": "6.2.0-master-012301",
		//"cmii-uav-platform-pilot2-to-cloud": "6.1.0-32030-123101",
		//"cmii-uav-industrial-portfolio": "6.1.0-20241125-121702",
	}

	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()

	}

}
