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

import cn.hutool.core.util.StrUtil;
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.YarnQueue;
import com.lanyuanxiaoyao.service.yarn.configuration.YarnConfiguration;
import com.lanyuanxiaoyao.service.yarn.response.QueueListResponse;
import com.lanyuanxiaoyao.service.yarn.service.QueueService;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * Queue
 *
 * @author lanyuanxiaoyao
 * @date 2023-04-23
 */
@Service("QueueAutoRefreshService")
public class QueueAutoRefreshServiceImpl implements QueueService {
    private static final Logger logger = LoggerFactory.getLogger(QueueAutoRefreshServiceImpl.class);

    private final ObjectMapper mapper;
    private final YarnConfiguration yarnConfiguration;

    public QueueAutoRefreshServiceImpl(ObjectMapper mapper, YarnConfiguration yarnConfiguration) {
        this.mapper = mapper;
        this.yarnConfiguration = yarnConfiguration;
    }

    private static final AtomicReference<ImmutableList<YarnQueue>> CACHE = new AtomicReference<>(Lists.immutable.empty());

    @Scheduled(fixedRate = 50000)
    public void refresh() throws JsonProcessingException {
        String queryUrl = URLUtil.completeUrl(yarnConfiguration.getWebUrl(), "/ws/v1/cluster/scheduler");
        String body = HttpUtil.createGet(queryUrl).setMaxRedirectCount(10).execute().body();
        QueueListResponse response = mapper.readValue(body, QueueListResponse.class);
        ImmutableList<YarnQueue> queues = Lists.immutable.ofAll(response.getScheduler().getSchedulerInfo().getQueues().getQueue());
        CACHE.set(queues);
    }

    @Override
    public ImmutableList<YarnQueue> list() throws JsonProcessingException {
        return CACHE.get();
    }

    @Override
    public YarnQueue detail(String name) throws Exception {
        return list()
                .select(q -> StrUtil.equals(q.getQueueName(), name))
                .getFirstOptional()
                .orElseThrow(() -> new Exception("cannot found " + name));
    }
}
