package com.lanyuanxiaoyao.service.yarn.service.impl;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnClusters;
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnRootQueue;
import com.lanyuanxiaoyao.service.yarn.response.ClusterInfoResponse;
import com.lanyuanxiaoyao.service.yarn.service.ClusterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * Cluster
 *
 * @author lanyuanxiaoyao
 * @date 2023-04-23
 */
@Service
@CacheConfig(cacheManager = "normal-cache")
public class ClusterServiceImpl implements ClusterService {
    private static final Logger logger = LoggerFactory.getLogger(ClusterServiceImpl.class);

    private final ObjectMapper mapper;
    private final YarnClusters yarnClusters;

    public ClusterServiceImpl(YarnClusters yarnClusters, Jackson2ObjectMapperBuilder builder) {
        this.yarnClusters = yarnClusters;

        this.mapper = builder.build();
    }

    @Cacheable(value = "cluster-info", sync = true)
    @Retryable(Throwable.class)
    @Override
    public YarnRootQueue info(String cluster) throws JsonProcessingException {
        String webUrl = yarnClusters.getWebUrl(cluster);
        String queryUrl = URLUtil.completeUrl(webUrl, "/ws/v1/cluster/scheduler");
        String body = HttpUtil.createGet(queryUrl).setMaxRedirectCount(10).execute().body();
        return mapper.readValue(body, ClusterInfoResponse.class).getScheduler().getSchedulerInfo()
                .setCluster(cluster)
                .setWebUrl(URLUtil.completeUrl(webUrl, "/cluster/scheduler"));
    }
}
