package io.renren.modules.kubesphere.service;

import com.google.gson.JsonObject;
import io.renren.common.utils.GsonUtil;
import io.renren.modules.kubesphere.config.KubeSphereConfig;
import io.renren.modules.kubesphere.interceptor.KubeSphereTokenInterceptor;
import io.renren.modules.kubesphere.module.KubeSphereRequestBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 应用服务
 *
 * @author chenrj
 * @email 1412736935@qq.com
 * @since 2021/8/14
 */
@Service
public class ApplicationService {

    private final RestTemplate restTemplate;

    @Value("${harborUrl}")
    private String harborUrl;

    @Autowired
    public ApplicationService(RestTemplate restTemplate) {
        // 设置Token 等信息
        restTemplate.getInterceptors().add(new KubeSphereTokenInterceptor());
        this.restTemplate = restTemplate;
    }

    /**
     * 应用预检v2
     *
     * @param args
     * @return
     */
    public String applicationDryRun_V2(HashMap<String, String> args) {
        String applicationName = args.get("applicationName");
        String namespace = args.get("namespace");
        String creator = args.get("creator");
        String request = String.format(KubeSphereRequestBuilder.APPLICATION_DRY_RUN, applicationName,
                namespace, applicationName, creator, applicationName);
        System.out.println("请求体:" + request);
        // 格式化请求体
        Map<String, Object> hashmap = GsonUtil.convertJsonToMap(request);
        ResponseEntity<String> response = restTemplate.postForEntity(KubeSphereConfig.URL.APPLICATION_DRY_RUN, hashmap, String.class);
        return response.getBody();
    }

    /**
     * 部署预检v2
     *
     * @param args
     * @return
     */
    public String deploymentDryRun_V2(HashMap<String, String> args) {
        String namespace = args.get("namespace");
        String serviceName = args.get("serviceName");
        String applicationName = args.get("applicationName");
        String formatServiceNameWithVersion = formatServiceNameWithVersion(serviceName, "v1");
        String creator = args.get("creator");
        int serviceReplicas = Integer.parseInt(args.get("serviceReplicas"));
        String containerName = args.get("containerName");
        String imageName = args.get("imageNlibraryame");
        String portName = args.get("portName");
        int containerPort = Integer.parseInt(args.get("containerPort"));
        int servicePort = Integer.parseInt(args.get("servicePort"));

        String request = String.format(KubeSphereRequestBuilder.DEPLOYMENT_DRY_RUN, namespace, serviceName,
                applicationName, formatServiceNameWithVersion, creator, serviceReplicas,
                serviceName, applicationName, serviceName, applicationName, containerName,
                imageName, portName, containerPort, servicePort);
        System.out.println("请求体" + request);
        // 格式化请求体
        Map<String, Object> hashmap = GsonUtil.convertJsonToMap(request);
        ResponseEntity<String> response = restTemplate.postForEntity(KubeSphereConfig.URL.DEPLOYMENT_DRY_RUN, hashmap, String.class);
        return response.getBody();
    }

    /**
     * 服务预检v2
     *
     * @param args
     * @return
     */
    public String serviceDryRun_V2(HashMap<String, String> args) {
        String namespace = args.get("namespace");
        String serviceName = args.get("serviceName");
        String applicationName = args.get("applicationName");
        String creator = args.get("creator");
        String portsName = args.get("portsName");
        int containerPort = Integer.parseInt(args.get("containerPort"));
        int servicePort = Integer.parseInt(args.get("servicePort"));

        String request = String.format(KubeSphereRequestBuilder.SERVICE_DRY_RUN, namespace,
                serviceName, applicationName, creator, serviceName, serviceName,
                applicationName, serviceName, applicationName,
                portsName, containerPort, servicePort);
        System.out.println("请求体" + request);
        // 格式化请求体
        Map<String, Object> hashmap = GsonUtil.convertJsonToMap(request);
        ResponseEntity<String> response = restTemplate.postForEntity(KubeSphereConfig.URL.SERVICE_DRY_RUN, hashmap, String.class);
        return response.getBody();
    }

    /**
     * 应用v2
     *
     * @param args
     * @return
     */
    public String application_V2(HashMap<String, String> args) {
        String applicationName = args.get("applicationName");
        String namespace = args.get("namespace");
        String creator = args.get("creator");

        String request = String.format(KubeSphereRequestBuilder.APPLICATION, applicationName,
                namespace, applicationName, creator, applicationName);

        System.out.println("请求体:" + request);
        // 格式化请求体
        Map<String, Object> hashmap = GsonUtil.convertJsonToMap(request);
        ResponseEntity<String> response = restTemplate.postForEntity(KubeSphereConfig.URL.APPLICATION, hashmap, String.class);
        return response.getBody();
    }


    /**
     * 部署v2
     *
     * @param args
     * @return
     */
    public String deployment_V2(HashMap<String, String> args) {
        String namespace = args.get("namespace");
        String serviceName = args.get("serviceName");
        String applicationName = args.get("applicationName");
        String formatServiceNameWithVersion = formatServiceNameWithVersion(serviceName, "v1");
        String creator = args.get("creator");
        int serviceReplicas = Integer.parseInt(args.get("serviceReplicas"));
        String containerName = args.get("containerName");
        String imageName = args.get("imageName");
        String portName = args.get("portName");
        int containerPort = Integer.parseInt(args.get("containerPort"));
        int servicePort = Integer.parseInt(args.get("servicePort"));

        String request = String.format(KubeSphereRequestBuilder.DEPLOYMENT, namespace, serviceName,
                applicationName, formatServiceNameWithVersion, creator, serviceReplicas,
                serviceName, applicationName, serviceName, applicationName, containerName,
                imageName, portName, containerPort, servicePort);
        System.out.println("请求体" + request);
        // 格式化请求体
        Map<String, Object> hashmap = GsonUtil.convertJsonToMap(request);
        ResponseEntity<String> response = restTemplate.postForEntity(KubeSphereConfig.URL.DEPLOYMENT, hashmap, String.class);
        return response.getBody();
    }

    /**
     * 服务v2
     *
     * @param args
     * @return
     */
    public String service_V2(HashMap<String, String> args) {
        String namespace = args.get("namespace");
        String serviceName = args.get("serviceName");
        String applicationName = args.get("applicationName");
        String creator = args.get("creator");
        String portsName = args.get("portsName");
        int containerPort = Integer.parseInt(args.get("containerPort"));
        int servicePort = Integer.parseInt(args.get("servicePort"));

        String request = String.format(KubeSphereRequestBuilder.SERVICE, namespace,
                serviceName, applicationName, creator, serviceName, serviceName,
                applicationName, serviceName, applicationName,
                portsName, containerPort, servicePort);
        System.out.println("请求体" + request);
        // 格式化请求体
        Map<String, Object> hashmap = GsonUtil.convertJsonToMap(request);
        ResponseEntity<String> response = restTemplate.postForEntity(KubeSphereConfig.URL.SERVICE, hashmap, String.class);
        return response.getBody();
    }

    public HashMap<String, String> getArgs(String jsonDta) {
        JsonObject jsonObject = GsonUtil.convertJsonObject(jsonDta);
        String imageName = jsonObject.get("imageName").getAsString();
        imageName = imageName.toLowerCase();
        HashMap<String, String> args = new HashMap<>();
//        JsonObject jsonObject = GsonUtil.convertJsonObject(jsonDta);
//        String imageName = jsonObject.get("imageName").toString();
        String namespace = "mkcloud";
        String creator = "admin";
        String serviceName = imageName + "service";
        String applicationName = imageName + "application";
        String serviceReplicas = "1";
        String portsName = "http-chenrj";
        String containerPort = "5000";
        String servicePort = "5000";
        String containerName = generateContainerName();
        imageName = harborUrl+"/library/" + imageName + ":latest";

        args.put("imageName", imageName);
        args.put("namespace", namespace);
        args.put("creator", creator);
        args.put("serviceName", serviceName);
        args.put("applicationName", applicationName);
        args.put("serviceReplicas", serviceReplicas);
        args.put("portsName", portsName);
        args.put("containerPort", containerPort);
        args.put("servicePort", servicePort);
        args.put("containerName", containerName);
        return args;
    }


    /**
     * 格式化应用进入预检后的名字
     *
     * @param application
     * @return
     */
    public String formatIngressApplicationName(String application) {
        String res = "";
        res = application + "-ingress-" + randomlyGenerateCharacters(6);
        return res;
    }


    /**
     * 随机生成n位的36进制字符串
     *
     * @param n
     * @return
     */
    public String randomlyGenerateCharacters(int n) {
        Random random = new Random();
        String res = "";
        for (int i = 0; i < n; i++) {
            int rand = random.nextInt(36);
            if (rand < 10) {
                res += (char) ('0' + rand);
            } else {
                res += (char) ('a' + (rand - 10));
            }
        }
        return res;
    }

    public String formatServiceNameWithVersion(String serviceName, String version) {
        String res = "";
        res = serviceName + "-" + version;
        return res;
    }

    /**
     * 生成容器名字
     *
     * @return
     */
    public String generateContainerName() {
        return "container-" + randomlyGenerateCharacters(6);
    }
}
