package com.rv.component.utils.log;

import android.text.TextUtils;
import android.util.Log;

import com.rv.component.utils.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*******
 * 把日志写到文件里面
 */
public class Log2File {
    private static final String TAG = "日志文件";
    private static ExecutorService executorService = null;

    protected static ExecutorService getExecutorService() {
        return executorService;
    }

    public static void log2file(final LogLevel level, final String tag, final String msg) {
        if (executorService == null) {
            executorService = Executors.newSingleThreadExecutor();
        }
        if (executorService != null) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    LogFormatter formatter = new LogFormatter();
                    String log = formatter.format(level, tag, msg);
                    FilePathGgenerator ggenerator = new FilePathGgenerator(LogUtil.getContext(), formatter.formatDate(), ".log");
                    String path = ggenerator.getPath();
                    String dir = ggenerator.dir;
                    try {
                        File parent = new File(dir);
                        if (!parent.exists()) {
                            parent.mkdirs();
                        }
                        File file = new File(path);
                        FileOutputStream outputStream = new FileOutputStream(file,true);
                        outputStream.write(log.getBytes());
                        outputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    protected static void setExecutorService(ExecutorService paramExecutorService) {
        executorService = paramExecutorService;
    }
}
