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.YarnApplication;
import com.lanyuanxiaoyao.service.yarn.configuration.YarnConfiguration;
import com.lanyuanxiaoyao.service.yarn.response.ApplicationsListResponse;
import com.lanyuanxiaoyao.service.yarn.service.JobService;
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;

/**
 * Job
 *
 * @author lanyuanxiaoyao
 * @date 2023-04-23
 */
@Service("JobAutoRefreshService")
public class JobAutoRefreshServiceImpl implements JobService {
    private static final Logger logger = LoggerFactory.getLogger(JobAutoRefreshServiceImpl.class);

    private final ObjectMapper mapper;
    private final YarnConfiguration yarnConfiguration;

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

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

    @Scheduled(fixedRate = 50000)
    public void refresh() throws JsonProcessingException {
        String queryUrl = URLUtil.completeUrl(yarnConfiguration.getWebUrl(), "/ws/v1/cluster/apps");
        String body = HttpUtil.createGet(queryUrl).setMaxRedirectCount(10).execute().body();
        ImmutableList<YarnApplication> apps = mapper.readValue(body, ApplicationsListResponse.class).getApps().getApp();
        CACHE.set(apps);
    }

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

    @Override
    public ImmutableList<YarnApplication> listEquals(String name) {
        return list().select(app -> StrUtil.equals(app.getName(), name));
    }

    @Override
    public ImmutableList<YarnApplication> listLike(String name) {
        return list().select(app -> StrUtil.contains(app.getName(), name));
    }

    @Override
    public void kill(String applicationId) {
    }

    @Override
    public YarnApplication detail(String applicationId) throws Exception {
        return list().select(app -> StrUtil.equals(app.getId(), applicationId))
                .getFirstOptional().orElseThrow(() -> new Exception("cannot found " + applicationId));
    }
}
