package image

import (
	"os"
	"path/filepath"
	"strings"
	"wdd.io/agent-common/logger"
)

var log = logger.Log

var unSupported = "UN-SUPPORT-APP-NAME"

const CmiiHarborPrefix = "harbor.cdcyy.com.cn/cmii/"

func ImageFullNameToAppName(imageFullName string) (appName string) {

	// harbor.cdcyy.cn/cmii/cmii-uav-platform:5.4.0 ==> cmii-uav-platform

	// 10.1.1.1:8033/cmii/ok:1.2  不支持 不允许存在
	// rancher/fleet:v0.3.4

	// ossr/srs:v5.0.1
	// nginx:latest
	// bitnami/minio:2022.5.4
	// simonrupf/chronyd:0.4.3

	s := strings.Split(imageFullName, ":")
	if len(s) == 1 {
		// nginx
		return imageFullName
	}
	// 10.1.1.1:8033/cmii/ok:1.2
	// harbor.cdcyy.cn/cmii/cmii-uav-platform:5.4.0 ==> cmii-uav-platform
	// rancher/fleet:v0.3.4
	// ossr/srs:v5.0.1
	// nginx:latest
	// bitnami/minio:2022.5.4
	// simonrupf/chronyd:0.4.3

	middle := s[len(s)-2]
	split := strings.Split(middle, "/")
	return split[len(split)-1]
}

func ImageFullNameToImageTag(imageFullName string) (imageTag string) {
	s := strings.Split(imageFullName, ":")[1]

	if strings.Contains(s, ":") {
		// 10.1.1.1:8033/cmii/ok:1.2
		return strings.Split(imageFullName, ":")[2]
	}

	return s
}

func ImageFullNameToImageNameAndTag(imageFullName string) (imageName, imageTag string) {

	s := strings.Split(imageFullName, ":")
	if len(s) == 1 {
		// nginx
		return imageFullName, "latest"
	}
	// 10.1.1.1:8033/cmii/ok:1.2
	// harbor.cdcyy.cn/cmii/cmii-uav-platform:5.4.0 ==> cmii-uav-platform
	// rancher/fleet:v0.3.4
	// ossr/srs:v5.0.1
	// nginx:latest
	// bitnami/minio:2022.5.4
	// simonrupf/chronyd:0.4.3

	middle := s[len(s)-2]
	split := strings.Split(middle, "/")
	return split[len(split)-1], s[len(s)-1]

}

// ImageFullNameToGzipFileName 必须输出长度为4的内容 =出现得次数为3
func ImageFullNameToGzipFileName(imageFullName string) (gzipFileName string) {
	// rancher/fleet:v0.3.4

	// ossr/srs:v5.0.1  ==> docker=cmii=srs=v5.0.1.tar.gz
	// nginx:latest
	// bitnami/minio:2022.5.4
	// simonrupf/chronyd:0.4.3

	s := strings.Split(imageFullName, ":")
	if len(s) == 1 {
		// nginx
		return "docker=cmii=" + imageFullName + "=latest.tar.gz"
	} else if len(s) > 2 {
		// 10.1.1.1:8033/cmii/ok:1.2  不支持 不允许存在
		return "unsupport=" + imageFullName
	}
	middle := s[len(s)-2]
	split := strings.Split(middle, "/")
	if len(split) == 1 {
		// nginx:latest
		return "docker=cmii=" + s[0] + "=" + s[1] + ".tar.gz"
	}

	if strings.HasPrefix(imageFullName, "harbor.cdcyy.com.cn") {
		// harbor.cdcyy.cn/cmii/cmii-uav-platform:5.4.0 ==> cmlc=cmii=cmii-uav-platform=5.4.0.tar.gz
		// harbor.cdcyy.cn/cmii/cmii-uav-platform:5.4.0
		// harbor.cdcyy.com.cn/cmii/cmlc-ai/cmlc-ai-operator:v5.2.0-t4-no-dino

		return "cmlc=cmii=" + split[len(split)-1] + "=" + s[1] + ".tar.gz"

	} else if strings.Contains(imageFullName, "rancher") {
		return "docker=rancher=" + split[len(split)-1] + "=" + s[1] + ".tar.gz"
	} else {
		// ossrs/srs:v4.0.136
		return "docker=cmii=" + split[len(split)-1] + "=" + s[1] + ".tar.gz"
	}

	return "unsupport=" + imageFullName
}

// ImageNameToTargetImageFullName 将ImageName转换为目标TargetHosts的全名称，ImageName的格式为 短名称或者长名称 均可
func ImageNameToTargetImageFullName(imageName, targetHarborHost string) string {

	targetProject := "cmii"
	if strings.HasPrefix(imageName, "rancher") {
		// rancher/rancher:v2.5.7 rancher名称的形式
		targetProject = "rancher"
	}

	countOfSplit := strings.Count(imageName, "/")
	split := strings.Split(imageName, "/")
	targetImageName := imageName

	switch countOfSplit {
	case 0:
		// nginx:latest
		targetImageName = targetHarborHost + "/" + targetProject + "/" + imageName
		break
	default:
		// 10.250.0.10:8033/cmii/cmii-uav-gateway:v1.0.0
		targetImageName = targetHarborHost + "/" + targetProject + "/" + split[countOfSplit]
		break
	}

	//if strings.HasPrefix(imageFullName, CmiiHarborPrefix) {
	//	imageFullName = strings.TrimPrefix(imageFullName, CmiiHarborPrefix)
	//} else if strings.HasPrefix(imageFullName, "docker.io") {
	//	imageFullName = strings.TrimPrefix(imageFullName, "docker.io")
	//}
	//// rancher/123:v123
	//if strings.HasPrefix(imageFullName, "rancher") {
	//	return targetHostFullName + "/" + imageFullName
	//}
	//// ossr/srs:v4.0.5
	//if strings.Contains(imageFullName, "/") {
	//	imageFullName = strings.Split(imageFullName, "/")[1]
	//}
	//
	//// srs:v4.0.5
	//// cmii-uav-platform:5.4.0
	//s := targetHostFullName + "/cmii/" + imageFullName
	//log.InfoF("ImageFullName: [%s] to TargetImageFullName: [%s]", imageName, targetImageName)
	return targetImageName
}

func GzipFileNameToImageFullName(gzipFileName string) (imageFullName string) {
	if !strings.HasSuffix(gzipFileName, ".tar.gz") {
		log.ErrorF(" %s is not end with .tar.gz", gzipFileName)
		return ""
	}
	gzipFileName = strings.TrimSuffix(gzipFileName, ".tar.gz")

	if strings.HasPrefix(gzipFileName, "docker=library") {
		// docker=library=busybox=latest.tar.gz
		return strings.Split(gzipFileName, "=")[2] + ":" + strings.Split(gzipFileName, "=")[3]
	}

	if strings.HasPrefix(gzipFileName, "docker") {
		return strings.Split(gzipFileName, "=")[1] + "/" + strings.Split(gzipFileName, "=")[2] + ":" + strings.Split(gzipFileName, "=")[3]
	}

	if strings.HasPrefix(gzipFileName, "cmlc=cmii=") {
		return strings.Split(gzipFileName, "=")[2] + ":" + strings.Split(gzipFileName, "=")[3]
	}

	return gzipFileName
}

func GzipFileNameToImageNameAndTag(gzipFileName string) (imageName, imageTag string) {
	if !strings.HasSuffix(gzipFileName, ".tar.gz") {
		log.ErrorF(" %s is not end with .tar.gz", gzipFileName)
		return "", ""
	}
	gzipFileName = strings.TrimSuffix(gzipFileName, ".tar.gz")

	if strings.HasPrefix(gzipFileName, "docker=library") {
		// docker=library=busybox=latest.tar.gz
		return strings.Split(gzipFileName, "=")[2], strings.Split(gzipFileName, "=")[3]
	}

	if strings.HasPrefix(gzipFileName, "docker") {
		// docker=kubernetes=kubernetes-dashboard=v2.4.0.tar.gz
		return strings.Split(gzipFileName, "=")[1] + "/" + strings.Split(gzipFileName, "=")[2], strings.Split(gzipFileName, "=")[3]
	}

	if strings.HasPrefix(gzipFileName, "cmlc=cmii=") {
		return strings.Split(gzipFileName, "=")[2], strings.Split(gzipFileName, "=")[3]
	}

	return "", ""
}

func GzipFolderPathToCmiiImageTagMaps(gzipFolderPath string) (frontendImageVersionMap, backendImageVersionMap, srsImageVersionMap map[string]string) {

	frontendImageVersionMap = make(map[string]string)
	backendImageVersionMap = make(map[string]string)
	srsImageVersionMap = make(map[string]string)

	filepath.WalkDir(gzipFolderPath, func(path string, d os.DirEntry, err error) error {
		//fmt.Println(path)
		if d == nil {
			return nil
		}
		name := d.Name()
		if strings.HasSuffix(name, ".tar.gz") {
			imageName, imageTag := GzipFileNameToImageNameAndTag(name)
			if strings.Contains(imageName, "platform") {
				frontendImageVersionMap[imageName] = imageTag
			} else if strings.Contains(imageName, "srs") {
				srsImageVersionMap[imageName] = imageTag
			} else if strings.Contains(imageName, "operator") {
				srsImageVersionMap[imageName] = imageTag
			} else {
				backendImageVersionMap[imageName] = imageTag
			}
		}

		return nil
	})

	return frontendImageVersionMap, backendImageVersionMap, srsImageVersionMap
}

func CmiiImageMapFromImageFullNameList(cmiiImageFullNameList []string) (cmiiImageVersionMap map[string]string) {

	cmiiImageVersionMap = make(map[string]string)
	for _, imageFullName := range cmiiImageFullNameList {
		imageName, imageTag := ImageFullNameToImageNameAndTag(imageFullName)
		cmiiImageVersionMap[imageName] = imageTag
	}

	return cmiiImageVersionMap
}

func FrontendBackendSrsImageMapFromCmiiImageMap(cmiiImageVersionMap map[string]string) (frontendImageVersionMap, backendImageVersionMap, srsImageVersionMap map[string]string) {

	frontendImageVersionMap = make(map[string]string)
	backendImageVersionMap = make(map[string]string)
	srsImageVersionMap = make(map[string]string)

	for imageName, imageTag := range cmiiImageVersionMap {
		if strings.Contains(imageName, "platform") {
			frontendImageVersionMap[imageName] = imageTag
		} else if strings.Contains(imageName, "srs") {
			srsImageVersionMap[imageName] = imageTag
		} else if strings.Contains(imageName, "operator") {
			srsImageVersionMap[imageName] = imageTag
		} else {
			backendImageVersionMap[imageName] = imageTag
		}
	}

	return frontendImageVersionMap, backendImageVersionMap, srsImageVersionMap
}
