package cn.reghao.devops.logstash.service;

import cn.reghao.devops.logstash.ws.WsClient;
import cn.reghao.devops.logstash.config.LogFile;
import cn.reghao.jutil.jdk.thread.ThreadPoolWrapper;

import java.util.List;
import java.util.concurrent.*;

/**
 * @author reghao
 * @date 2022-05-20 16:23:34
 */
public class FileReader {
    private final ExecutorService threadPool = ThreadPoolWrapper.threadPool("logstash");
    private final ScheduledExecutorService scheduledThreadPool = ThreadPoolWrapper.scheduledThreadPool("logstash1", 5);
    private final String wsUrl;
    private final List<LogFile> logFiles;

    public FileReader(String wsUrl, List<LogFile> logFiles) {
        this.wsUrl = wsUrl;
        this.logFiles = logFiles;
    }

    public void start() {
        String app = "nginx";
        String host = "nginx";
        String params = String.format("app=%s&host=%s", app, host);
        String url = String.format("%s?%s", wsUrl, params);
        WsClient wsClient = new WsClient(url);
        wsClient.connect();
        for (LogFile logFile: logFiles) {
            String filePath = logFile.getFilePath();
            try {
                TailReader tailReader = new TailReader(filePath, wsClient);
                threadPool.submit(tailReader);
                //scheduledThreadPool.scheduleAtFixedRate(tailReader, 0, 1, TimeUnit.SECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
