package io.renren.modules.kubesphere.service;

import io.renren.common.utils.GsonUtil;
import io.renren.modules.kubesphere.config.KubeSphereConfig;
import io.renren.modules.kubesphere.interceptor.KubeSphereTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author chenrj
 * @email 1412736935@qq.com
 * @since 2021/8/11
 */
@Service
public class StorageVolumeService {

    private final RestTemplate restTemplate;

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

    public String createStorageVolume(String jsonData) {
        String createStorageVolume = "{\"apiVersion\":\"v1\",\"kind\":\"PersistentVolumeClaim\",\"metadata\":{\"namespace\":\"%s\",\"name\":\"%s\",\"annotations\":{\"kubesphere.io/alias-name\":\"%s\",\"kubesphere.io/description\":\"%s\",\"kubesphere.io/creator\":\"%s\"}},\"spec\":{\"accessModes\":[\"ReadWriteOnce\"],\"resources\":{\"requests\":{\"storage\":\"%s\"}},\"storageClassName\":\"local\"}}";
        Map<String, Object> parameter = GsonUtil.convertJsonToMap(jsonData);
        String namespace = parameter.get("namespace").toString();
        String name = parameter.get("name").toString();
        String aliasName = parameter.get("alias").toString();
        String description = parameter.get("description").toString();
        String creator = parameter.get("creator").toString();
        String storage = parameter.get("storage").toString();

        Map<String, Object> hashmap = GsonUtil.convertJsonToMap(
                String.format(createStorageVolume,
                        namespace, name, aliasName, description, creator, storage));
        ResponseEntity<String> s2ires = restTemplate.postForEntity(KubeSphereConfig.URL.STORAGE_VOLUME_CREATE, hashmap, String.class);
        return s2ires.getBody().toString();
    }


}
