package deploy

import (
	"bytes"
	"fmt"
	v1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	appsv1 "k8s.io/client-go/applyconfigurations/apps/v1"
	"sigs.k8s.io/yaml"
	"text/template"
	"wdd.io/agent-go/utils"
)

type CommonEnvironmentConfig struct {
	WebIP      string
	WebPort    string
	HarborIP   string
	HarborPort string
}

type CmiiBackendDeploymentConfig struct {
	Namespace    string
	AppName      string
	ImageTag     string
	TagVersion   string
	Replicas     string
	NodePort     string
	NeedPvcCache bool
	CustomJvmOpt string
}

type CmiiFrontendDeploymentConfig struct {
	Namespace  string
	AppName    string
	ImageTag   string
	TagVersion string
	Replicas   string
	ShortName  string
}

func (backend CmiiBackendDeploymentConfig) ParseToApplyConf() *appsv1.DeploymentApplyConfiguration {

	// 解析模板

	tmpl, err := template.New("cmiiBackendDeploymentTemplate").Parse(cmiiBackendDeploymentTemplate)
	if err != nil {
		panic(err)
	}

	// 应用数据并打印结果
	var result bytes.Buffer
	err = tmpl.Execute(&result, backend)
	if err != nil {
		panic(err)
	}

	// 创建Deployment对象
	deployment := v1.Deployment{}
	err = yaml.Unmarshal(result.Bytes(), &deployment)
	if err != nil {
		panic(err)
	}

	utils.BeautifulPrint(&deployment)

	// service
	parse, err := template.New("cmiiBackendServiceTemplate").Parse(cmiiBackendServiceTemplate)
	if err != nil {
		panic(err)
	}
	// 应用数据并打印结果
	var resulta bytes.Buffer
	err = parse.Execute(&resulta, backend)
	if err != nil {
		panic(err)
	}

	fmt.Println(resulta.String())

	// 创建Deployment对象
	service := corev1.Service{}
	err = yaml.Unmarshal(resulta.Bytes(), &service)
	if err != nil {
		panic(err)
	}

	utils.BeautifulPrint(&service)

	return nil
}
