package com.draw.painting.line.manager;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Range;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.activity.ComponentActivity;
import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.camera.core.Camera;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class AppHelper {

    public static int getRange(Camera camera) {
        Range<Integer> exposureCompensationRange = camera.getCameraInfo().getExposureState().getExposureCompensationRange();
        Integer upper = exposureCompensationRange.getUpper();
        Integer lower = exposureCompensationRange.getLower();
        return upper;
    }

    public static void setStatusBarTextColor(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    /**
     * 启用边缘到边缘显示（EdgeToEdge）
     * @param activity ComponentActivity
     */
    public static void enableEdgeToEdge(ComponentActivity activity) {
        EdgeToEdge.enable(activity);
        Window window = activity.getWindow();
        // 状态栏透明
        window.setStatusBarColor(Color.TRANSPARENT);
        // 导航栏不透明，使用白色背景
        window.setNavigationBarColor(Color.WHITE);
    }

    /**
     * 为根视图设置 WindowInsets 监听器，自动处理系统栏间距（只处理顶部和左右）
     * @param rootView 根视图
     */
    public static void setupWindowInsetsListener(View rootView) {
        ViewCompat.setOnApplyWindowInsetsListener(rootView, new OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                v.setPadding(systemBars.left, systemBars.top, systemBars.right, 0);
                return insets;
            }
        });
    }

    /**
     * 为底部导航栏设置 WindowInsets 监听器，处理底部系统栏间距
     * @param bottomNav 底部导航栏视图
     */
    public static void setupBottomNavigationInsets(View bottomNav) {
        ViewCompat.setOnApplyWindowInsetsListener(bottomNav, new OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                v.setPadding(v.getPaddingLeft(), v.getPaddingTop(), v.getPaddingRight(), systemBars.bottom);
                return insets;
            }
        });
    }

    /**
     * 为内容容器设置底部导航栏的 padding，避免内容被遮挡
     * @param contentView 内容容器视图
     */
    public static void setupBottomNavPadding(View contentView) {
        ViewCompat.setOnApplyWindowInsetsListener(contentView, new OnApplyWindowInsetsListener() {
            @NonNull
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                v.setPadding(systemBars.left, systemBars.top, systemBars.right,
                    systemBars.bottom);
                return insets;
            }
        });
    }

    /**
     * 为视图设置状态栏高度的 margin，用于全屏界面中需要避开状态栏的元素
     * @param view 需要设置 margin 的视图
     */
    public static void setupStatusBarMargin(View view) {
        ViewCompat.setOnApplyWindowInsetsListener(view, new OnApplyWindowInsetsListener() {
            @NonNull
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                android.view.ViewGroup.MarginLayoutParams params = 
                    (android.view.ViewGroup.MarginLayoutParams) v.getLayoutParams();
                params.topMargin = systemBars.top + 12; // 状态栏高度 + 额外间距
                v.setLayoutParams(params);
                return insets;
            }
        });
    }

    /**
     * 为视图设置底部导航栏高度的 margin，用于全屏界面中需要避开底部导航栏的元素
     * @param view 需要设置 margin 的视图
     * @param extraMarginDp 额外的底部间距（dp）
     */
    public static void setupBottomNavMargin(View view, int extraMarginDp) {
        ViewCompat.setOnApplyWindowInsetsListener(view, new OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                android.view.ViewGroup.MarginLayoutParams params = 
                    (android.view.ViewGroup.MarginLayoutParams) v.getLayoutParams();
                // 将 dp 转换为 px
                float density = v.getContext().getResources().getDisplayMetrics().density;
                int extraMarginPx = (int) (extraMarginDp * density);
                params.bottomMargin = systemBars.bottom + extraMarginPx;
                v.setLayoutParams(params);
                return insets;
            }
        });
    }

    public static Point getScreen(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        Point point = new Point();
        point.x = width;
        point.y = height;
        return point;
    }
    public static boolean checkPermission(Context context,String[] permissions) {
        boolean result = true;
        for (String per : permissions) {
            if (ActivityCompat.checkSelfPermission(context, per) != PackageManager.PERMISSION_GRANTED) {
                result = false;
            }
        }
        return result;

    }
    public static Bitmap loadImageFromAssets(Context context, String fileName) {
        Bitmap bitmap = null;
        AssetManager assetManager = context.getAssets();
        try (InputStream is = assetManager.open(fileName)) {
            bitmap = BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            return bitmap;
        }

        return bitmap;

    }

    public static List<String> fileExistsInAssets(Context context, String dir) {

        List<String> pathList = new ArrayList<String>();
        try {
            AssetManager assetManager = context.getAssets();
            String[] files = assetManager.list(dir);

            if (files != null) {
                for (String name : files) {
                    pathList.add(dir + "/" + name);
                }
                return pathList;
            }
        } catch (IOException e) {

            return pathList;
        }
        return pathList;
    }


    public static List<Bitmap> getAnimalsName(Context context, String dir) {
        List<Bitmap> list = new ArrayList<>();
        for (int i = 0; i < 40; i++) {

            Bitmap bitmap = loadImageFromAssets(context, dir + "/" + (i + 1) + ".jpg");
            if (bitmap == null) {
                break;
            } else {
                list.add(bitmap);
            }

        }
        return list;
    }

    public static PackageInfo getInfo(Context context) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException exception) {

            return null;
        }
        return packageInfo;
    }


    public static float getDistance(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

}

