package com.bsmlab.dfx.agent.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.valves.AccessLogValve;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Paths;
import java.time.Duration;

@Slf4j
@Component
@RequiredArgsConstructor
public class AccessLogConfiguration implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
    private final AgentConfigReader agentConfigReader;

    /**
     * Access log 설정
     * @param factory
     */
    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        AgentConfigDto agentConfigDto = this.agentConfigReader.getAgentConfigDto();
        String logFilePath = Paths.get(agentConfigDto.getLogging().getLogDirectory(), "access").toString();
        AccessLogValve accessLogValve = new AccessLogValve();
        accessLogValve.setPattern("combined");
        accessLogValve.setDirectory(logFilePath);
        accessLogValve.setSuffix(".log");
        accessLogValve.setRotatable(true);
        accessLogValve.setRenameOnRotate(true);
        accessLogValve.setFileDateFormat(".yyyy-MM-dd");
        accessLogValve.setRequestAttributesEnabled(true);
        factory.addContextValves(accessLogValve);
    }

    /**
     * Access log 삭제. 설정 파일의 maxHistory 기준
     */
    @Scheduled(cron = "0 0 3 * * *")
    public void cleanAccessLog() {
        AgentConfigDto agentConfigDto = this.agentConfigReader.getAgentConfigDto();
        File logFileDirFile = new File(Paths.get(agentConfigDto.getLogging().getLogDirectory()).toString(), "access");
        File[] files = logFileDirFile.listFiles((dir, name) -> name.startsWith("access_log"));
        long maxHistory = agentConfigDto.getLogging().getMaxHistory();
        long cutoff = System.currentTimeMillis() - Duration.ofDays(maxHistory).toMillis();
        if (files != null) {
            for(File file : files) {
                if(file.lastModified() < cutoff) {
                    file.deleteOnExit();
                }
            }
        }
    }
}
