package com.rnboat.framework.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.blankj.utilcode.util.AppUtils;
import com.rnboat.framework.ConfigManager;
import com.rnboat.framework.diskcache.AsyncDiskCache;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LogcatHelper {

    private static LogcatHelper INSTANCE = null;
    private static String PATH_LOGCAT;
    private static int LOG_FILE_KB = 512;
    private static String POST_FILE_URL = "http://vem-grey-api.1000.com/files/upload";
    private LogDumper mLogDumper = null;
    private int mPId;
    private Context mContext;

    public interface OnUploadSuccessCallback {
        void onUploadSuccess();
    }
    /**
     * 初始化目录
     */
    public void init(Context context) {
//        if (Environment.getExternalStorageState().equals(
//                Environment.MEDIA_MOUNTED)) {// 优先保存到SD卡中
//            PATH_LOGCAT = Environment.getExternalStorageDirectory()
//                    .getAbsolutePath() + File.separator + "Logcat";
//        } else {// 如果SD卡不存在，就保存到本应用的目录下
//            PATH_LOGCAT = dirPath + File.separator + DateUtils.getFileName();
//        }
        mContext = context;
        List lstFilePaths = new ArrayList();
        String dirPath = context.getFilesDir().getAbsolutePath() + File.separator + "Logcat";
        String currentFileName = String.format("%s_%s_%s", AppUtils.getAppPackageName(), AsyncDiskCache.syncReadCache("loginID", String.class), DateUtils.getFileName());
        PATH_LOGCAT = dirPath + File.separator + currentFileName;

        File file = new File(PATH_LOGCAT);
        if (!file.exists()) {
            file.mkdirs();
        }

        File dirFile = new File(dirPath);
        for (File tempFile: dirFile.listFiles()) {
            if (!tempFile.getName().equals(currentFileName) && tempFile.isDirectory()) {
                String zipPath = String.format("%s.zip", tempFile.getAbsolutePath());
                if (CompressUtil.zip(tempFile.getAbsolutePath(), zipPath, "") == null) {
                    Log.d("error", "Zip File failed!:" + zipPath);
                }
                else {
                    lstFilePaths.add(zipPath);
                    SystemUtil.deleteAllFilesOfDir(tempFile);
                }
            }
            else if (tempFile.getName().contains("zip")) {
                lstFilePaths.add(tempFile.getAbsolutePath());
            }
        }

        uploadFiles(lstFilePaths, null);
    }

    public static LogcatHelper getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new LogcatHelper(context);
        }
        return INSTANCE;
    }

    private LogcatHelper(Context context) {
        init(context);
        mPId = android.os.Process.myPid();
    }

    public void start() {
        if (mLogDumper == null) {
            mLogDumper = new LogDumper(String.valueOf(mPId));
            mLogDumper.start();
        }
    }

    public void stop() {
        if (mLogDumper != null) {
            mLogDumper.stopLogs();
            mLogDumper = null;
        }
    }

    private class LogDumper extends Thread {

        private Process logcatProc;
        private BufferedReader mReader = null;
        private boolean mRunning = true;
        String cmds = null;
        private String mPID;
        private FileOutputStream out = null;
        public LogDumper(String pid) {
            mPID = pid;
            try {
                out = new FileOutputStream(new File(PATH_LOGCAT, DateUtils.getDateEN() + ".log"));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /**
             *
             * 日志等级：*:v , *:d , *:w , *:e , *:f , *:s
             *
             * 显示当前mPID程序的 E和W等级的日志.
             *
             * */

            // cmds = "logcat *:e *:w | grep \"(" + mPID + ")\"";
            // cmds = "logcat  | grep \"(" + mPID + ")\"";//打印所有日志信息
            // cmds = "logcat -s way";//打印标签过滤信息
            cmds = "logcat  | grep \"(" + mPID + ")\"";

        }

        public void stopLogs() {
            mRunning = false;
        }

        @Override
        public void run() {
            try {
                logcatProc = Runtime.getRuntime().exec(cmds);
                mReader = new BufferedReader(new InputStreamReader(
                        logcatProc.getInputStream()), 1024);
                String line;

                float size = 0;
                while (mRunning && (line = mReader.readLine()) != null) {
                    if (!mRunning) {
                        break;
                    }
                    if (line.length() == 0 || out == null || !line.contains(mPID)) {
                        continue;
                    }
                    if (size <= LOG_FILE_KB) {
                        byte[] outByte = (line + "\n").getBytes();
                        out.write(outByte);
                        size += outByte.length / 1024.0f;
                    }
                    else {
                        size = 0;
                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            out = null;
                        }
                        String dirPath = mContext.getFilesDir().getAbsolutePath() + File.separator + "Logcat";
                        String currentFileName = String.format("%s_%s_%s", AppUtils.getAppPackageName(), AsyncDiskCache.syncReadCache("loginID", String.class), DateUtils.getFileName());
                        PATH_LOGCAT = dirPath + File.separator + currentFileName;

                        File file = new File(PATH_LOGCAT);
                        if (!file.exists()) {
                            file.mkdirs();
                        }


                        out = new FileOutputStream(new File(PATH_LOGCAT, DateUtils.getDateEN() + ".log"));
                        byte[] outByte = (DateUtils.getDateEN() + "  " + line + "\n").getBytes();
                        out.write(outByte);
                        size += outByte.length / 1024.0f;
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (logcatProc != null) {
                    logcatProc.destroy();
                    logcatProc = null;
                }
                if (mReader != null) {
                    try {
                        mReader.close();
                        mReader = null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    out = null;
                }

            }

        }

    }

    public void uploadFiles(final List<String> lstFilePaths, final OnUploadSuccessCallback callback) {
        if (lstFilePaths.size() == 0)
            return;

        //开始Post请求
        OKHttpUtils.doPostRequest(POST_FILE_URL, lstFilePaths, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "error------> "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    for (String path: lstFilePaths) {
                        SystemUtil.deleteAllFilesOfDir(new File(path));
                    }

                    if (callback != null) {
                        callback.onUploadSuccess();
                    }
                }
                Log.i("TAG", "success---->"+response.body().string());
            }
        });
    }

    public void uploadAllFiles(OnUploadSuccessCallback callback) {
        List lstFilePaths = new ArrayList();
        String dirPath = mContext.getFilesDir().getAbsolutePath() + File.separator + "Logcat";
        String currentFileName = String.format("%s_%s_%s", AppUtils.getAppPackageName(), AsyncDiskCache.syncReadCache("loginID", String.class), DateUtils.getFileName());
        PATH_LOGCAT = dirPath + File.separator + currentFileName;

        File file = new File(PATH_LOGCAT);
        if (!file.exists()) {
            file.mkdirs();
        }

        File dirFile = new File(dirPath);
        for (File tempFile: dirFile.listFiles()) {
            if (tempFile.isDirectory()) {
                String zipPath = String.format("%s.zip", tempFile.getAbsolutePath());
                if (CompressUtil.zip(tempFile.getAbsolutePath(), zipPath, "") == null) {
                    Log.d("error", "Zip File failed!:" + zipPath);
                }
                else {
                    lstFilePaths.add(zipPath);
                    SystemUtil.deleteAllFilesOfDir(tempFile);
                }
            }
            else if (tempFile.getName().contains("zip")) {
                lstFilePaths.add(tempFile.getAbsolutePath());
            }
        }

        uploadFiles(lstFilePaths, callback);
    }
}
