package com.cool.bang.modules.system.service.impl;

import com.cool.bang.modules.system.service.ILoggerService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 *  Web 日志查看
 *
 * @author PeiZhi Guo
 * 2023/10/25 20:27
 */
@Service
public class LoggerServiceImpl implements ILoggerService {

    private static final Logger logger = LoggerFactory.getLogger(LoggerFactory.class);

    @Value("${logging.file.path}")
    private String logPath;

    private static final String CURRENT_LOG = "%s/%s.log";

    private static final String HISTORY_LOG = "%s/%s/%s-%s.0.log";

    @Override
    public String readLoggers(String level, Integer count, String date) {
        String logText = "";

        String logFilePath;
        if (StringUtils.isNotBlank(date)) {
            logFilePath = String.format(HISTORY_LOG, logPath, level, level, date);
        } else {
            logFilePath = String.format(CURRENT_LOG, logPath, level);
        }

        RandomAccessFile rf = null;
        try {
            rf = new RandomAccessFile(logFilePath, "r");
            long nextend = rf.length() - 1L;
            if (nextend < 0L) {
                nextend = 0L;
            }
            long start = rf.getFilePointer();
            rf.seek(nextend);
            int c = -1;
            for (int lineCount = 0; nextend >= start && lineCount < count; --nextend) {
                c = rf.read();
                if (c == 10 || c == 13) {
                    String line = rf.readLine();
                    if (!StringUtils.isBlank(line)) {
                        logText = new String(line.getBytes("ISO-8859-1"), "UTF-8") + "</br>" + logText;
                        ++lineCount;
                    }
                }
                if (nextend == 0L) {
                    rf.seek(0L);
                    String line = rf.readLine();
                    if (!StringUtils.isBlank(line)) {
                        logText = new String(line.getBytes("ISO-8859-1"), "UTF-8") + logText;
                    }
                } else {
                    rf.seek(nextend - 1L);
                }
            }
        } catch (Exception e) {
            LoggerServiceImpl.logger.error(e.getMessage(), e);
        } finally {
            try {
                if (rf != null) {
                    rf.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return logText;
    }

}
