package com.ttstd.dialer.utils;

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

import com.ttstd.dialer.BuildConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Logger {
    // 日志级别枚举
    public enum LogLevel {
        DEBUG, INFO, WARN, ERROR
    }

    private static final String TAG = "AppLogger";
    private static final String LOG_FILE_NAME = "app_log.txt";
    private static File logFile;
    private static LogLevel logLevel = LogLevel.DEBUG; // 默认日志级别
    private static boolean isDebugMode = BuildConfig.DEBUG; // 默认关闭Debug输出

    // 初始化日志系统（需在应用启动时调用）
    public static void initialize(Context context, boolean debugMode) {
        isDebugMode = debugMode;
        try {
            File storageDir = context.getExternalFilesDir("log");
            logFile = new File(storageDir, LOG_FILE_NAME);
        } catch (Exception e) {
            Log.e(TAG, "Log file init failed: " + e.getMessage());
        }
    }

    // 设置全局日志级别
    public static void setLogLevel(LogLevel level) {
        logLevel = level;
    }

    // 核心日志方法
    private static void log(LogLevel level, Object context, String name, String message) {
        if (level.ordinal() < logLevel.ordinal()) return; // 低于设定级别不记录
        String tag;
        if (TextUtils.isEmpty(context.getClass().getSimpleName())) {
            tag = context.toString();
        } else {
            tag = context.getClass().getSimpleName();
        }
        String logMsg = formatLog(level, tag, name, message);
        writeToFile(logMsg); // 始终写入文件

        if (isDebugMode) {
            outputToConsole(level, tag, name, message); // 仅Debug模式输出到控制台
        }
    }

    // 格式化日志（含时间戳、线程信息）
    private static String formatLog(LogLevel level, String tag, String name, String message) {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()).format(new Date());
        String threadName = Thread.currentThread().getName();
        return String.format("%s [%s] %s/%s: %s %s\n", time, threadName, level.name(), tag, name, message);
    }

    // 写入日志文件
    private static void writeToFile(String logMsg) {
        if (logFile == null) return;
        try (FileWriter writer = new FileWriter(logFile, true)) {
            writer.append(logMsg);
        } catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.getMessage());
        }
    }

    // 输出到Android控制台（Logcat）
    private static void outputToConsole(LogLevel level, String tag, String name, String message) {
        switch (level) {
            case DEBUG:
                Log.d(tag, name + " : " + message);
                break;
            case INFO:
                Log.i(tag, name + " : " + message);
                break;
            case WARN:
                Log.w(tag, name + " :  " + message);
                break;
            case ERROR:
                Log.e(tag, name + " : " + message);
                break;
        }
    }

    // 快捷调用方法（自动使用类名作为TAG）
    public static void d(Object context, String name, String message) {
        log(LogLevel.DEBUG, context.getClass().getSimpleName(), name, message);
    }

    public static void i(Object context, String name, String message) {
        log(LogLevel.INFO, context.getClass().getSimpleName(), name, message);
    }

    public static void w(Object context, String name, String message) {
        log(LogLevel.WARN, context.getClass().getSimpleName(), name, message);
    }

    public static void e(Object context, String name, String message) {
        log(LogLevel.ERROR, context, name, message);
    }

    public static void d(Object context, String name) {
        log(LogLevel.DEBUG, context.getClass().getSimpleName(), name, "");
    }

    public static void i(Object context, String name) {
        log(LogLevel.INFO, context.getClass().getSimpleName(), name, "");
    }

    public static void w(Object context, String name) {
        log(LogLevel.WARN, context.getClass().getSimpleName(), name, "");
    }

    public static void e(Object context, String name) {
        log(LogLevel.ERROR, context.getClass().getSimpleName(), name, "");
    }
}