package cn.reghao.devops.logstash.service;

import cn.reghao.devops.logstash.ws.WsClient;
import cn.reghao.devops.logstash.model.NginxLog;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import lombok.extern.slf4j.Slf4j;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

/**
 * @author reghao
 * @date 2022-05-20 11:41:08
 */
@Slf4j
public class TailReader implements Runnable {
    private final String filePath;
    private final RandomAccessFile raf;
    private long pointer;
    private final WsClient wsClient;

    public TailReader(String filePath, WsClient wsClient) throws FileNotFoundException {
        this.filePath = filePath;
        this.raf  = new RandomAccessFile(filePath, "r");
        this.pointer = 0;
        this.wsClient = wsClient;
    }

    @Override
    public void run() {
        try {
            long length = raf.length();
            raf.seek(length);
            while (!Thread.interrupted()) {
                try {
                    String line = raf.readLine();
                    while (line == null) {
                        Thread.sleep(3_000);
                        line = raf.readLine();
                    }

                    while (line != null) {
                        parseAndPersist(line);
                        line = raf.readLine();
                    }
                /*if (length > pointer) {
                    raf.seek(pointer);
                    String line = raf.readLine();
                    while (line != null) {
                        parseAndPersist(line);
                        line = raf.readLine();
                    }
                    pointer = length;
                } else {
                    log.info("已读取到 {} 文件末尾, 休眠 10s 后再尝试读取", filePath);
                    Thread.sleep(10_000);
                }*/
                } catch (Exception e) {
                }
            }
        } catch (Exception e ) {

        }
    }

    private void parseAndPersist(String line) {
        try {
            NginxLog nginxLog = JsonConverter.jsonToObject(line, NginxLog.class);
            wsClient.send("", nginxLog);
        } catch (Exception ignore) {
        }
    }
}
