package com.idle.wall.idletool;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Debug;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.idle.wall.IdleApp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

public class Comutils {
    public static final String key_info = "key_info";
    public static final String key_index = "key_index";
    private static final String TAG = "Comutils";

    public static String getCovertStr(InputStream stream) {
        if (stream == null) {
            Log.w(TAG, "getCovertStr: 输入流为null");
            return "";
        }

        try (StringWriter writer = new StringWriter();
             BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {

            char[] buffer = new char[1024];
            int readLen;
            while ((readLen = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, readLen);
            }
            return writer.toString();

        } catch (IOException e) {
            Log.e(TAG, "流转字符串失败", e);
            return "";
        }
    }

    // 单参数版本（核心）
    public static int dp2px(int dp) {
        Context context = IdleApp.mAppContext;
        if (context == null) {
            Log.w(TAG, "dp2px: 全局Context为null，返回原始dp值");
            return dp;
        }
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    // 兼容旧方法名
    public static int dp2Px(int dp) {
        return dp2px(dp);
    }

    // 新增重载：支持传Context（解决所有参数不匹配问题）
    public static int dp2px(Context context, int dp) {
        if (context == null) {
            Log.w(TAG, "dp2px: Context为null，降级使用全局上下文");
            return dp2px(dp);
        }
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static void initFull(Activity activity, boolean isLightStatusBar) {
        if (activity == null) {
            Log.w(TAG, "initFull: Activity为null，跳过状态栏设置");
            return;
        }

        Window window = activity.getWindow();
        if (window == null) return;

        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(android.graphics.Color.TRANSPARENT);

        View decorView = window.getDecorView();
        int uiFlags = decorView.getSystemUiVisibility();
        if (isLightStatusBar) {
            uiFlags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        } else {
            uiFlags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }
        decorView.setSystemUiVisibility(uiFlags);
    }

    private static Bitmap getBitmap(Drawable drawable) {
        if (drawable == null) {
            Log.w(TAG, "getBitmap: Drawable为null");
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            return bitmap != null ? bitmap : Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
        }

        int width = drawable.getIntrinsicWidth() <= 0 ? 100 : drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight() <= 0 ? 100 : drawable.getIntrinsicHeight();

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

    public static String saveDrawableToFile(Drawable drawable, String saveFilePath) {
        if (drawable == null || saveFilePath == null || saveFilePath.isEmpty()) {
            Log.w(TAG, "saveDrawableToFile: Drawable或保存路径为空");
            return null;
        }

        Bitmap bitmap = getBitmap(drawable);
        if (bitmap == null) {
            Log.e(TAG, "saveDrawableToFile: Bitmap转换失败");
            return null;
        }

        File file = new File(saveFilePath);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) {
            Log.e(TAG, "saveDrawableToFile: 创建目录失败：" + parentDir.getAbsolutePath());
            bitmap.recycle();
            return null;
        }

        try (FileOutputStream fos = new FileOutputStream(file)) {
            boolean success = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            if (success) {
                Log.d(TAG, "Drawable保存成功：" + file.getAbsolutePath());
                return file.getAbsolutePath();
            } else {
                Log.e(TAG, "Bitmap压缩失败");
                return null;
            }
        } catch (IOException e) {
            Log.e(TAG, "保存Drawable到文件失败", e);
            return null;
        } finally {
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
    }

    public static void printUsedMemory(Context context) {
        if (context == null) {
            Log.w(TAG, "printUsedMemory: Context为null");
            return;
        }

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            Log.w(TAG, "printUsedMemory: ActivityManager获取失败");
            return;
        }

        int pid = android.os.Process.myPid();
        Debug.MemoryInfo[] memoryInfoArray = activityManager.getProcessMemoryInfo(new int[]{pid});
        if (memoryInfoArray == null || memoryInfoArray.length == 0) {
            Log.w(TAG, "printUsedMemory: 未获取到内存信息");
            return;
        }

        Debug.MemoryInfo memoryInfo = memoryInfoArray[0];
        float totalPssMB = memoryInfo.getTotalPss() / 1024.0f;
        float privateDirtyMB = memoryInfo.getTotalPrivateDirty() / 1024.0f;
        float sharedDirtyMB = memoryInfo.getTotalSharedDirty() / 1024.0f;

        Log.d("MemoryInfo", String.format("进程PID：%d", pid));
        Log.d("MemoryInfo", String.format("总PSS内存：%.2f MB", totalPssMB));
        Log.d("MemoryInfo", String.format("私有脏内存：%.2f MB", privateDirtyMB));
        Log.d("MemoryInfo", String.format("共享脏内存：%.2f MB", sharedDirtyMB));
    }

    public static int[] getScreenWidthHeight(Context context) {
        if (context == null) {
            Log.w(TAG, "getScreenWidthHeight: Context为null");
            return new int[]{0, 0};
        }

        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        Log.d(TAG, String.format("屏幕尺寸：宽=%dpx，高=%dpx", width, height));
        return new int[]{width, height};
    }
}