package com.lanyuanxiaoyao.service.yarn.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnQueue;
import java.util.LinkedList;
import java.util.Queue;
import org.eclipse.collections.api.block.function.Function;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.ImmutableList;
import org.eclipse.collections.api.list.MutableList;

/**
 * Queue
 *
 * @author lanyuanxiaoyao
 * @date 2023-04-23
 */
public interface QueueService {
    ImmutableList<YarnQueue> list(String cluster) throws JsonProcessingException;

    YarnQueue detail(String cluster, String name) throws Exception;

    default Function<YarnQueue, Iterable<YarnQueue>> flatChildren() {
        return queue -> {
            MutableList<YarnQueue> children = Lists.mutable.of(queue);
            Queue<YarnQueue> handleQueue = new LinkedList<>();
            handleQueue.add(queue);

            YarnQueue parent = handleQueue.poll();
            while (parent != null) {
                try {
                    if (ObjectUtil.isNotNull(parent.getQueues())) {
                        for (YarnQueue child : queue.getQueues().getQueue()) {
                            child.setQueueName(StrUtil.format("{}.{}", parent.getQueueName(), child.getQueueName()));
                            children.add(child);
                            handleQueue.add(child);
                        }
                    }
                } finally {
                    parent = handleQueue.poll();
                }
            }
            return children;
        };
    }
}
