package cn.hgits.loglibrary;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.hgsoft.debuglogshow.DebugLogActivity;
import com.hgsoft.log.LogUtil;
import com.hgsoft.log.MarsXLogInit;
import net.lingala.zip4j.exception.ZipException;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    AppCompatButton btnInitLog;
    AppCompatButton btnInitTwelveLog;
    AppCompatButton btnInitTwokbLog;
    AppCompatButton btnCloseLog;
    AppCompatButton btnPrint;
    AppCompatButton btnCreateFourteenLog;
    AppCompatButton btnSaveDiffLogFile;
    AppCompatButton btnZipCurrentLog;
    AppCompatButton btnZipAllLog;
    AppCompatButton btnShowLog;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnInitLog = findViewById(R.id.btn_init_log);
        btnInitTwelveLog = findViewById(R.id.btn_init_twelve_log);
        btnInitTwokbLog = findViewById(R.id.btn_init_two_kb_size_log);
        btnCloseLog = findViewById(R.id.btn_close_log);
        btnPrint = findViewById(R.id.btn_print_log);
        btnCreateFourteenLog = findViewById(R.id.btn_create_fourteen_log);
        btnSaveDiffLogFile = findViewById(R.id.btn_save_diff_log_file);
        btnZipCurrentLog = findViewById(R.id.btn_zip_current_log);
        btnZipAllLog = findViewById(R.id.btn_zip_all_log);
        btnShowLog = findViewById(R.id.btn_show_log);

        btnInitLog.setOnClickListener(onClickListener);
        btnInitTwelveLog.setOnClickListener(onClickListener);
        btnInitTwokbLog.setOnClickListener(onClickListener);
        btnCloseLog.setOnClickListener(onClickListener);
        btnPrint.setOnClickListener(onClickListener);
        btnCreateFourteenLog.setOnClickListener(onClickListener);
        btnSaveDiffLogFile.setOnClickListener(onClickListener);
        btnZipCurrentLog.setOnClickListener(onClickListener);
        btnZipAllLog.setOnClickListener(onClickListener);
        btnShowLog.setOnClickListener(onClickListener);
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int viewId = v.getId();
            switch (viewId) {
                case R.id.btn_init_log:
                    initLog();
                    LogUtil.i(TAG, systemInfo(MainActivity.this));
                    LogUtil.appenderFlush(false);
                    break;
                case R.id.btn_init_twelve_log:
                    initTwelveLog();
                    LogUtil.i(TAG, systemInfo(MainActivity.this));
                    LogUtil.appenderFlush(false);
                    break;
                case R.id.btn_init_two_kb_size_log:
                    initTwoKbSizeLog();
                    LogUtil.i(TAG, systemInfo(MainActivity.this));
                    LogUtil.appenderFlush(true);
                    break;
                case R.id.btn_close_log:
                    LogUtil.appenderClose();
                    break;
                case R.id.btn_print_log:
                    LogUtil.v(TAG, "测试日志-v");
                    LogUtil.d(TAG, "测试日志-d");
                    LogUtil.i(TAG, "测试日志-i");
                    LogUtil.w(TAG, "测试日志-w");
                    LogUtil.e(TAG, "测试日志-e");
                    LogUtil.appenderFlush(true);
                    break;
                case R.id.btn_create_fourteen_log:
                    createFourteenDayLogFile();
                    break;
                case R.id.btn_save_diff_log_file:
                    LogUtil.appenderClose();
                    initLog();
                    break;
                case R.id.btn_zip_current_log:
                    File currentLogZipFile = null;
                    try {
                        currentLogZipFile = LogUtil.getCurrentUserLogFileZip(MainActivity.this);
                    } catch (ZipException e) {
                        LogUtil.e(TAG, "异常信息：" + e.getStackTrace());
                    }
                    if (currentLogZipFile != null) {
                        LogUtil.i(TAG, "currentLogZipFile路径：" + currentLogZipFile.getAbsolutePath());
                        ZipFile zipFile = null;
                        try {
                            zipFile = new ZipFile(currentLogZipFile.getAbsolutePath());
                            Enumeration<? extends ZipEntry> entries = zipFile.entries();
                            LogUtil.i(TAG, "压缩包中包含的文件");
                            while(entries.hasMoreElements()){
                                ZipEntry entry = entries.nextElement();
                                LogUtil.i(TAG, "名称：" + entry.getName());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case R.id.btn_zip_all_log:
                    File allLogZipFile = null;
                    try {
                        allLogZipFile = LogUtil.getAppAllLogFileZip(MainActivity.this);
                    } catch (ZipException e) {
                        LogUtil.e(TAG, "异常信息：" + e.getStackTrace());
                    }
                    if (allLogZipFile != null) {
                        LogUtil.i(TAG, "allLogZipFile路径：" + allLogZipFile.getAbsolutePath());
                        ZipFile zipFile = null;
                        try {
                            zipFile = new ZipFile(allLogZipFile.getAbsolutePath());
                            Enumeration<? extends ZipEntry> entries = zipFile.entries();
                            LogUtil.i(TAG, "压缩包中包含的文件");
                            while(entries.hasMoreElements()){
                                ZipEntry entry = entries.nextElement();
                                LogUtil.i(TAG, "名称：" + entry.getName());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case R.id.btn_show_log:
                    Intent intent = new Intent(MainActivity.this, DebugLogActivity.class);
                    intent.putExtra("logEndWith", LogUtil.TAG);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    };


    private void initLog() {
        MarsXLogInit.getInstance().setDebugStatus(BuildConfig.DEBUG);
        if (BuildConfig.DEBUG) {
            MarsXLogInit.getInstance().setPUBKEY("");
            MarsXLogInit.getInstance().setConsoleLogOpen(true);
            MarsXLogInit.getInstance().setLogFileNamePrefix("Debug_" + System.currentTimeMillis());
        } else {
            MarsXLogInit.getInstance().setPUBKEY("94e62d97637f357fbd20f0c1f667a67c2f675e158e46015dd0cc54cb3995d0a5d468f7e98b20aec266effb61ec0a2321fb1f8c61af72bf76567921a0d8305005");
            MarsXLogInit.getInstance().setConsoleLogOpen(false);
            MarsXLogInit.getInstance().setLogFileNamePrefix("Release_" + System.currentTimeMillis());
        }
        MarsXLogInit.getInstance().openXlog(this);
        LogUtil.logPrintInfo((priority, tag, message) -> {
            switch (priority) {
                case LEVEL_DEBUG:
                    Log.d(TAG, message);
                    break;
                case LEVEL_ERROR:
                    Log.e(TAG, message);
                    break;
                case LEVEL_INFO:
                    Log.i(TAG, message);
                    break;
                case LEVEL_WARNING:
                    Log.w(TAG, message);
                    break;
                case LEVEL_VERBOSE:
                default:
                    Log.v(TAG, message);
                    break;
            }
        });
    }


    private void initTwelveLog() {
        MarsXLogInit.getInstance().setDebugStatus(BuildConfig.DEBUG);
        if (BuildConfig.DEBUG) {
            MarsXLogInit.getInstance().setPUBKEY("");
            MarsXLogInit.getInstance().setConsoleLogOpen(true);
            MarsXLogInit.getInstance().setLogFileNamePrefix("Debug_" + System.currentTimeMillis());
            MarsXLogInit.getInstance().setLogFileSaveDays(12);
        } else {
            MarsXLogInit.getInstance().setPUBKEY("94e62d97637f357fbd20f0c1f667a67c2f675e158e46015dd0cc54cb3995d0a5d468f7e98b20aec266effb61ec0a2321fb1f8c61af72bf76567921a0d8305005");
            MarsXLogInit.getInstance().setConsoleLogOpen(false);
            MarsXLogInit.getInstance().setLogFileNamePrefix("Release_" + System.currentTimeMillis());
            MarsXLogInit.getInstance().setLogFileSaveDays(12);
        }
        MarsXLogInit.getInstance().openXlog(this);
        LogUtil.logPrintInfo((priority, tag, message) -> {
            switch (priority) {
                case LEVEL_DEBUG:
                    Log.d(TAG, message);
                    break;
                case LEVEL_ERROR:
                    Log.e(TAG, message);
                    break;
                case LEVEL_INFO:
                    Log.i(TAG, message);
                    break;
                case LEVEL_WARNING:
                    Log.w(TAG, message);
                    break;
                case LEVEL_VERBOSE:
                default:
                    Log.v(TAG, message);
                    break;
            }
        });
    }

    private void initTwoKbSizeLog() {
        MarsXLogInit.getInstance().setDebugStatus(BuildConfig.DEBUG);
        if (BuildConfig.DEBUG) {
            MarsXLogInit.getInstance().setPUBKEY("");
            MarsXLogInit.getInstance().setConsoleLogOpen(true);
            MarsXLogInit.getInstance().setLogFileNamePrefix("Debug_" + System.currentTimeMillis());
            MarsXLogInit.getInstance().setLogFileMaxSize(2 * 1024);
        } else {
            MarsXLogInit.getInstance().setPUBKEY("94e62d97637f357fbd20f0c1f667a67c2f675e158e46015dd0cc54cb3995d0a5d468f7e98b20aec266effb61ec0a2321fb1f8c61af72bf76567921a0d8305005");
            MarsXLogInit.getInstance().setConsoleLogOpen(false);
            MarsXLogInit.getInstance().setLogFileNamePrefix("Release_" + System.currentTimeMillis());
            MarsXLogInit.getInstance().setLogFileMaxSize(2 * 1024);
        }
        MarsXLogInit.getInstance().openXlog(this);
        LogUtil.logPrintInfo((priority, tag, message) -> {
            switch (priority) {
                case LEVEL_DEBUG:
                    Log.d(TAG, message);
                    break;
                case LEVEL_ERROR:
                    Log.e(TAG, message);
                    break;
                case LEVEL_INFO:
                    Log.i(TAG, message);
                    break;
                case LEVEL_WARNING:
                    Log.w(TAG, message);
                    break;
                case LEVEL_VERBOSE:
                default:
                    Log.v(TAG, message);
                    break;
            }
        });
    }

    private void createFourteenDayLogFile() {
        File externalFileDir = getExternalFilesDir("XLog");
        String logPath = null;
        if (externalFileDir != null) {
            logPath = externalFileDir.getAbsolutePath();
        }
        String fileName = MarsXLogInit.getInstance().getLogFileNamePrefix() + "_" + getPastDate(14, "yyyyMMdd") + ".xlog";
        File fourteenLogFile = new File(logPath + "/" + fileName);
        if (!fourteenLogFile.exists()) {
            try {
                boolean result = fourteenLogFile.createNewFile();
                LogUtil.i(TAG, "创建文件:" + fileName + ",结果:" + result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past 天数
     * @param formatString 格式化
     * @return 日期
     */
    private String getPastDate(final int past, final String formatString) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat(formatString, Locale.SIMPLIFIED_CHINESE);
        String result = format.format(today);
        return result;
    }


    private String systemInfo(Context context) {
        final StringBuilder sb = new StringBuilder();
        try {
            String appVersionName = context.getPackageManager().getPackageInfo(context.getApplicationInfo().packageName, 0).versionName;
            long appVersionCode = context.getPackageManager().getPackageInfo(context.getApplicationInfo().packageName, 0).versionCode;
            sb.append("APP.VESIONNAME:[").append(appVersionName);
            sb.append("] APP.VERSIONCODE:[").append(appVersionCode);
            sb.append("] VERSION.RELEASE:[").append(Build.VERSION.RELEASE);
            sb.append("] VERSION.CODENAME:[").append(Build.VERSION.CODENAME);
            sb.append("] VERSION.INCREMENTAL:[").append(Build.VERSION.INCREMENTAL);
            sb.append("] BOARD:[").append(Build.BOARD);
            sb.append("] DEVICE:[").append(Build.DEVICE);
            sb.append("] DISPLAY:[").append(Build.DISPLAY);
            sb.append("] FINGERPRINT:[").append(Build.FINGERPRINT);
            sb.append("] HOST:[").append(Build.HOST);
            sb.append("] MANUFACTURER:[").append(Build.MANUFACTURER);
            sb.append("] MODEL:[").append(Build.MODEL);
            sb.append("] PRODUCT:[").append(Build.PRODUCT);
            sb.append("] TAGS:[").append(Build.TAGS);
            sb.append("] TYPE:[").append(Build.TYPE);
            sb.append("] USER:[").append(Build.USER).append("]");
        } catch (Throwable e) {
            LogUtil.e(TAG, "异常信息:" + e.getMessage());
        }
        return sb.toString();
    }

}
