package com.wayne.www.waynelib.fdc.log_print;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.wayne.www.waynelib.ui.BuildConfig;
import com.wayne.www.waynelib.util.DateUtils;
import com.wayne.www.waynelib.util.HsLogTagFlag;
import com.wayne.www.waynelib.util.HsLogUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class SaveLogStrategyHs {
    @NonNull
    private final Handler handler;

    private static <T> T checkNotNull(T reference) {
        if (reference == null) {
            throw new NullPointerException();
        }
        return reference;
    }

    public SaveLogStrategyHs(@NonNull Handler handler) {
        this.handler = checkNotNull(handler);
    }


    public void log(int level, @Nullable String tag, @NonNull String message) {
        checkNotNull(message);
        handler.sendMessage(handler.obtainMessage(level, message));
    }

    static class WriteHandler extends Handler {

        private String folder;
        private String diskPath;
        private String folderChild;
        private final int maxFileSize;

        WriteHandler(@NonNull Looper looper, int maxFileSize) {
            super(checkNotNull(looper));
//            this.folder = checkNotNull(folder);
            diskPath = Environment.getExternalStorageDirectory().getPath() + File.separator + "iss_" + BuildConfig.BUILD_TYPE + "_toHs/";
            folderChild = DateUtils.getDateString(System.currentTimeMillis());
            folder = diskPath + folderChild;
            HsLogUtils.o(HsLogTagFlag.LOG_PRINT, folder);
            this.maxFileSize = maxFileSize;
        }

        @SuppressWarnings("checkstyle:emptyblock")
        @Override
        public void handleMessage(@NonNull Message msg) {
            String content = (String) msg.obj;
            FileWriter fileWriter = null;
            try {
                if (!folder.contains(DateUtils.getDateString(System.currentTimeMillis()))) {
                    folderChild = DateUtils.getDateString(System.currentTimeMillis());
                    folder = diskPath + folderChild;
                    HsLogUtils.o(HsLogTagFlag.LOG_PRINT, folder);
                }
                File logFile = getLogFile(folder, "iss_fdc_log");
                fileWriter = new FileWriter(logFile, true);
                writeLog(fileWriter, content);
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                if (fileWriter != null) {
                    try {
                        fileWriter.flush();
                        fileWriter.close();
                    } catch (IOException e1) {
                    }
                }
            }
        }

        private void writeLog(@NonNull FileWriter fileWriter, @NonNull String content) throws IOException {
            checkNotNull(fileWriter);
            checkNotNull(content);
            fileWriter.append("\n").append(content);
        }

        private File getLogFile(@NonNull String folderName, @NonNull String fileName) {
            checkNotNull(folderName);
            checkNotNull(fileName);

            File folder = new File(folderName);
            if (!folder.exists()) {
                if (!folder.mkdirs()) {
                    HsLogUtils.e(HsLogTagFlag.LOG_PRINT, "文件未创建成功，可能是读写权限没给");
                }
            }
//            int newFileCount = 0;
//            File newFile;
//            File existingFile = null;
//
//            newFile = new File(folder, String.format("%s_%s.txt", fileName, newFileCount));
//            while (newFile.exists()) {
//                existingFile = newFile;
//                newFileCount++;
//                newFile = new File(folder, String.format("%s_%s.txt", fileName, newFileCount));
//            }
//
//            if (existingFile != null) {
//                if (existingFile.length() >= maxFileSize) {
//                    return newFile;
//                }
//                return existingFile;
//            }
//            return newFile;
            return new File(folder, String.format("%s.txt", fileName));
//            return new File(folder, String.format("%s_%s.txt", fileName, new SimpleDateFormat("yyyyMMdd").format(new Date())));
        }
    }
}
