package com.xypower.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.StreamHandler;

public class RotatingHandler extends StreamHandler {

    private long mPrevMillis;
    private String mLogFilePath;

    public RotatingHandler(String filePath, Formatter formatter) {
        // super(null, formatter);

        mPrevMillis = 0;
        mLogFilePath = filePath;

        File file = new File(mLogFilePath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        if (file.exists()) {
            long millis = file.lastModified();
            millis -= millis % 1000;

            Date dt = new Date(millis);
            dt.setHours(0);
            dt.setMinutes(0);
            mPrevMillis = dt.getTime();
        }

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file, true);
        } catch (Exception ex) {

        }

        setFormatter(formatter);
        setOutputStream(out);
    }

    @Override
    public void publish(LogRecord record) {
        if (!isLoggable(record)) {
            return;
        }

        if (mPrevMillis == 0) {
            long millis = record.getMillis();
            millis -= millis % 1000;
            Date dt = new Date(millis);
            dt.setHours(0);
            dt.setMinutes(0);
            mPrevMillis = dt.getTime();
        } else {
            long millis = record.getMillis();
            if (millis - mPrevMillis >= 86400000) {
                // Date changed
                Date dt = new Date(mPrevMillis);
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                String str = fmt.format(dt);

                File file = new File(mLogFilePath);
                File parentFile = file.getParentFile();
                String fileName = file.getName();
                String baseName = null;
                String extName = null;
                int pos = fileName.lastIndexOf('.');
                if (pos > 0) {
                    baseName = fileName.substring(0, pos);
                    extName = fileName.substring(pos);
                } else {
                    baseName = fileName;
                    extName = "";
                }

                String newFileName = baseName + "-" + str;
                File newFile = null;
                int idx = 1;
                do {
                    newFile = new File(parentFile, newFileName + extName);
                    if (!newFile.exists()) {
                        try {
                            file.renameTo(newFile);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        break;
                    }

                    newFileName = fileName + "-" + str + "." + Integer.toString(idx);
                    idx ++;
                } while (true);

                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(mLogFilePath, true);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                setOutputStream(out);

                dt = new Date(millis);
                dt.setHours(0);
                dt.setMinutes(0);
                mPrevMillis = dt.getTime();
            }
        }

        super.publish(record);
        flush();
    }

}
