package com.eactive.eai.common.monitor;

import com.eactive.eai.common.server.Keys;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.property.PropManager;
import java.io.File;
import java.util.Calendar;
import java.util.TimerTask;

public class MonitorCleaner extends TimerTask {

    static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

    public static final String PROP_GROUP = "EAIServiceMonitor";
    public static final String FILE_PATH = "file.write.path";

    public void run() {
        if (logger.isInfo()) {
            logger.info("MonitorCleaner started - cleaning files older than 7 days");
        }

        try {
            PropManager pmanager = PropManager.getInstance();
            String propPath = pmanager.getProperty(PROP_GROUP, FILE_PATH);

            //filepath를 프로퍼티에 설정 안했으면...
            if (propPath == null || propPath.equals("")){
                propPath = ".";
            }

            String wlServer = System.getProperty(Keys.SERVER_KEY);
            String dirPath = propPath + "/" + wlServer;

            cleanOldFiles(dirPath);

        } catch (Exception e) {
            if (logger.isError()) {
                logger.error("Error while cleaning old monitor files: " + e.getMessage(), e);
            }
        }
    }

    private void cleanOldFiles(String dirPath) {
        if (logger.isDebug()) {
            logger.debug("Cleaning old files in directory: " + dirPath);
        }

        try {
            File dir = new File(dirPath);

            if (dir.exists() && dir.isDirectory()) {
                File[] files = dir.listFiles((d, name) -> name.startsWith("MonitorVoData_"));

                if (files != null) {
                    Calendar weekAgo = Calendar.getInstance();
                    weekAgo.add(Calendar.DATE, -7);

                    if (logger.isDebug()) {
                        logger.debug("Files older than: " +
                                String.format("%04d%02d%02d",
                                        weekAgo.get(Calendar.YEAR),
                                        weekAgo.get(Calendar.MONTH) + 1,
                                        weekAgo.get(Calendar.DATE)));
                    }

                    int deletedCount = 0;
                    for (File file : files) {
                        String fileName = file.getName();
                        if (fileName.length() >= 22) {
                            String fileDate = fileName.substring(14, 22);
                            try {
                                Calendar fileTime = Calendar.getInstance();
                                fileTime.set(
                                        Integer.parseInt(fileDate.substring(0, 4)),
                                        Integer.parseInt(fileDate.substring(4, 6)) - 1,
                                        Integer.parseInt(fileDate.substring(6, 8))
                                );

                                if (fileTime.before(weekAgo)) {
                                    if (file.delete()) {
                                        deletedCount++;
                                        if (logger.isInfo()) {
                                            logger.info("Deleted old monitor file: " + fileName);
                                        }
                                    }
                                } else {
                                    if (logger.isDebug()) {
                                        logger.debug("Keeping file: " + fileName);
                                    }
                                }
                            } catch (NumberFormatException e) {
                                if (logger.isWarn()) {
                                    logger.warn("Invalid date format in filename: " + fileName);
                                }
                            }
                        }
                    }

                    if (logger.isInfo()) {
                        logger.info("MonitorCleaner finished - deleted " + deletedCount + " old files");
                    }
                }
            }
        } catch (Exception e) {
            if (logger.isError()) {
                logger.error("Error in cleanOldFiles: " + e.getMessage(), e);
            }
        }
    }

    // 테스트용 main 메소드
    public static void main(String[] args) {
        String testDir = "C:/temp/test_monitor";

        MonitorCleaner cleaner = new MonitorCleaner();
        cleaner.cleanOldFiles(testDir);
    }
}