package com.hh.lib_base.log;




import android.os.Process;

import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.utils.device.DeviceUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <pre>
 *     @author yangchong
 *     blog  : https://github.com/yangchong211/YCStatusBar
 *     time  : 2018/06/4
 *     desc  : 写入和读取工具类
 *     revise:
 * </pre>
 */
public class PrintToFileUtil {

    private static ThreadPoolExecutor iOExecutor ;

    // 线程工厂
    private static ThreadFactory mThreadFactory ;

    public static ThreadFactory getmThreadFactory() {
        if(mThreadFactory==null){
            synchronized (PrintToFileUtil.class){
                if(mThreadFactory==null){
                    mThreadFactory = new ThreadFactory() {
                        private final AtomicInteger mCount = new AtomicInteger(1);

                        @Override
                        public Thread newThread(Runnable r) {
                            // 设置线程名字
                            Thread thread = new Thread(r, "ThreadPoolManager #" + mCount.getAndIncrement());
                            // 设置线程优先级
                            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                            return thread;
                        }
                    };
                }
            }
        }
        return mThreadFactory;
    }

    /**
     * 将内容直接写过文件中，自己设置路径
     * 这个是一边打印日志，一边将日志写入到file
     * 不建议直接new一个子线程做写入逻辑，建议开启线程池，避免到处开启线程损耗性能
     * @param input                     写入内容
     * @param filePath                  路径
     * @return
     */
    static boolean input2File(final String input, final String filePath) {

        if(iOExecutor==null) {
            synchronized (PrintToFileUtil.class) {
                if(iOExecutor==null) {
                    iOExecutor = new ThreadPoolExecutor(
                            5,
                            Integer.MAX_VALUE,
                            10,
                            TimeUnit.SECONDS,
                            new LinkedBlockingDeque<Runnable>(60),
                            getmThreadFactory());
                }
            }
        }
        Future<Boolean> submit = iOExecutor.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                synchronized (PrintToFileUtil.class) {
                    synchronized (PrintToFileUtil.class) {
                        try (BufferedWriter writer = new BufferedWriter(
                                new FileWriter(filePath, true))) {
                            writer.write(input);
                            writer.flush(); // 显式刷新缓冲区
                            return true;
                        } catch (IOException e) {
                            // Handle exception
                            e.printStackTrace();
                            return false;
                        } catch (Exception e3) {
                            e3.printStackTrace();
                            return false;
                        }
                    }
                }
            }
        });
        try {
            return submit.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return false;
    }

    static String printDeviceInfo() {
        final String head = "************* Log Head ****************" +
                "\nDevice SN          : " + DeviceUtils.getDeviceSN() +// sn
                "\nAPP 包名           : " + DeviceUtils.getAppPackageName(BaseApplication.getContext()) +
                "\nApp 版本号         : " + DeviceUtils.getAppVersionName(BaseApplication.getContext()) +
                "\nDevice 设备型号    : " + DeviceUtils.getDeviceModel() +
                "\nAndroid 系统版本   : " + DeviceUtils.getAndroidVersion() +
                "\nDevice 固件        : " + DeviceUtils.getDeviceDisplay() +
                "\nDevice IP          : " + DeviceUtils.getDeviceIP()+
                "\n************* Log Head ****************\n\n";
        return head;
    }


}