package com.lanyuanxiaoyao.service.forest.service.launcher;

import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnClusters;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.list.ImmutableList;
import org.eclipse.collections.api.map.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

/**
 * @author lanyuanxiaoyao
 * @date 2023-06-06
 */
@Service
public class LaunchersService {
    private static final Logger logger = LoggerFactory.getLogger(LaunchersService.class);

    private final ImmutableMap<String, LauncherService> serviceMap;

    public LaunchersService(
            YarnClusters yarnClusters,
            ApplicationContext applicationContext
    ) {
        Map<String, LauncherService> map = new HashMap<>(5);
        for (String cluster : yarnClusters.getActiveClusters()) {
            logger.info("Load {} cluster service", cluster);
            LauncherService service = applicationContext.getBean(StrUtil.format("{}LauncherService", StrUtil.toCamelCase(cluster)), LauncherService.class);
            map.put(cluster, service);
        }
        serviceMap = Maps.immutable.ofAll(map);
    }

    public LauncherService getService(String cluster) {
        if (serviceMap.containsKey(cluster)) {
            return serviceMap.get(cluster);
        }
        throw new RuntimeException(StrUtil.format("Cluster {} not found", cluster));
    }

    public ImmutableList<LauncherService> getServices() {
        return serviceMap.valuesView().toList().toImmutable();
    }

    public void compactionStop(Long flinkJobId, String alias) {
        for (LauncherService service : getServices()) {
            service.compactionStop(flinkJobId, alias);
        }
    }

    public void compactionStop(Long flinkJobId, String alias, Boolean disableMeta) {
        for (LauncherService service : getServices()) {
            service.compactionStop(flinkJobId, alias, disableMeta);
        }
    }

    public void compactionStop(String cluster, Long flinkJobId, String alias) {
        LauncherService service = getService(cluster);
        service.compactionStop(flinkJobId, alias);
    }

    public void compactionStopApp(String applicationId) {
        for (LauncherService service : getServices()) {
            service.compactionStopApp(applicationId);
        }
    }

    public void compactionStopApp(String cluster, String applicationId) {
        LauncherService service = getService(cluster);
        service.compactionStopApp(applicationId);
    }
}
