package com.draw.painting.canvas.core;

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.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.util.Range;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
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.WindowInsetsCompat;

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

public class SystemHelper {

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

    /**
     * 设置状态栏和导航栏的图标颜色
     * @param activity Activity实例
     * @param lightStatusBar 状态栏是否使用深色图标（浅色背景）
     * @param lightNavigationBar 导航栏是否使用深色图标（浅色背景）
     */
    public static void setSystemBarsLight(Activity activity, boolean lightStatusBar, boolean lightNavigationBar) {
        View decor = activity.getWindow().getDecorView();
        
        // 获取当前的 flags
        int flags = decor.getSystemUiVisibility();
        
        // 设置状态栏图标颜色
        if (lightStatusBar) {
            flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        } else {
            flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }
        
        // 设置导航栏图标颜色（API 26+）
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            if (lightNavigationBar) {
                flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
            } else {
                flags &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
            }
        }
        
        decor.setSystemUiVisibility(flags);
    }
    
    /**
     * 旧方法，保持向后兼容
     */
    public static void setStatusBarTextColor(Activity activity, boolean dark) {
        setSystemBarsLight(activity, dark, false);
    }
    
    /**
     * 设置系统导航栏颜色
     * @param activity Activity实例
     * @param color 导航栏背景色
     */
    public static void setNavigationBarColor(Activity activity, int color) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().setNavigationBarColor(color);
        }
    }
    
    /**
     * 强制设置白色导航栏 + 深色图标（用于故障排查）
     */
    public static void forceWhiteNavigationBar(Activity activity) {
        // 设置白色背景
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().setNavigationBarColor(0xFFFFFFFF);
        }
        
        // 强制设置深色图标
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            View decor = activity.getWindow().getDecorView();
            int visibility = decor.getSystemUiVisibility();
            visibility |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
            decor.setSystemUiVisibility(visibility);
            
            // 再次确认（强制刷新）
            decor.post(() -> {
                int vis = decor.getSystemUiVisibility();
                vis |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
                decor.setSystemUiVisibility(vis);
            });
        }
    }
    
    /**
     * 启用边缘到边缘显示（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() {
            @NonNull
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, @NonNull 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() {
            @NonNull
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, @NonNull 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, @NonNull 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 的视图
     * @param extraMarginDp 额外的底部间距（dp）
     */
    public static void setupBottomNavMargin(View view, int extraMarginDp) {
        ViewCompat.setOnApplyWindowInsetsListener(view, new OnApplyWindowInsetsListener() {
            @NonNull
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, @NonNull WindowInsetsCompat insets) {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                ViewGroup.MarginLayoutParams params = 
                    (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;
            }
        });
    }
    
    /**
     * 设置透明窗口背景（用于全屏相机等场景）
     * @param activity Activity实例
     */
    public static void setTransparentWindowBackground(Activity activity) {
        activity.getWindow().setBackgroundDrawable(null);
    }
    
    /**
     * 设置窗口背景颜色
     * @param activity Activity实例
     * @param color 背景颜色
     */
    public static void setWindowBackgroundColor(Activity activity, int color) {
        activity.getWindow().setBackgroundDrawable(new ColorDrawable(color));
    }
    
    /**
     * 为相机预览界面设置全屏沉浸式体验
     * - 只设置底部padding，让内容延伸到状态栏
     * - 给顶部控制按钮（如返回按钮）添加顶部margin
     * @param rootView 根视图
     * @param topControlView 顶部控制视图（如返回按钮），需要避开状态栏
     * @param extraTopMarginDp 顶部额外间距（dp）
     */
    public static void setupCameraFullScreen(View rootView, View topControlView, int extraTopMarginDp) {
        ViewCompat.setOnApplyWindowInsetsListener(rootView, new OnApplyWindowInsetsListener() {
            @NonNull
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, @NonNull WindowInsetsCompat insets) {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                
                // 只设置底部padding，不设置顶部（让相机预览延伸到状态栏）
                v.setPadding(0, 0, 0, systemBars.bottom);
                
                // 给顶部控制视图添加顶部margin，避免被状态栏遮挡
                if (topControlView != null && topControlView.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                    ViewGroup.MarginLayoutParams params = 
                        (ViewGroup.MarginLayoutParams) topControlView.getLayoutParams();
                    // 将 dp 转换为 px
                    float density = v.getContext().getResources().getDisplayMetrics().density;
                    int extraMarginPx = (int) (extraTopMarginDp * density);
                    params.topMargin = systemBars.top + extraMarginPx;
                    topControlView.setLayoutParams(params);
                }
                
                return insets;
            }
        });
    }
    
    /**
     * 为视图设置顶部状态栏高度的 margin
     * @param view 需要设置 margin 的视图
     * @param extraMarginDp 额外的顶部间距（dp）
     */
    public static void setupTopStatusBarMargin(View view, int extraMarginDp) {
        ViewCompat.setOnApplyWindowInsetsListener(view, new OnApplyWindowInsetsListener() {
            @NonNull
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, @NonNull WindowInsetsCompat insets) {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                ViewGroup.MarginLayoutParams params = 
                    (ViewGroup.MarginLayoutParams) v.getLayoutParams();
                // 将 dp 转换为 px
                float density = v.getContext().getResources().getDisplayMetrics().density;
                int extraMarginPx = (int) (extraMarginDp * density);
                params.topMargin = systemBars.top + extraMarginPx;
                v.setLayoutParams(params);
                return insets;
            }
        });
    }
    
    /**
     * 设置全屏沉浸式模式（隐藏状态栏和导航栏）
     * @param activity Activity实例
     */
    public static void enableFullScreenImmersive(Activity activity) {
        View decorView = activity.getWindow().getDecorView();
        decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        );
    }
    
    /**
     * 退出全屏沉浸式模式
     * @param activity Activity实例
     */
    public static void disableFullScreenImmersive(Activity activity) {
        View decorView = activity.getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
    }
    
    /**
     * 设置状态栏颜色
     * @param activity Activity实例
     * @param color 状态栏颜色
     */
    public static void setStatusBarColor(Activity activity, int color) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().setStatusBarColor(color);
        }
    }
    
    /**
     * 设置透明状态栏
     * @param activity Activity实例
     */
    public static void setTransparentStatusBar(Activity activity) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }
    
    /**
     * 设置透明导航栏
     * @param activity Activity实例
     */
    public static void setTransparentNavigationBar(Activity activity) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().setNavigationBarColor(Color.TRANSPARENT);
        }
    }
    
    /**
     * 配置全屏EdgeToEdge模式（完整版）
     * @param activity ComponentActivity实例
     * @param statusBarColor 状态栏颜色（Color.TRANSPARENT 为透明）
     * @param navigationBarColor 导航栏颜色（Color.TRANSPARENT 为透明）
     * @param lightStatusBar 状态栏是否使用深色图标（浅色背景时为true）
     * @param lightNavigationBar 导航栏是否使用深色图标（浅色背景时为true）
     */
    public static void setupFullScreenEdgeToEdge(ComponentActivity activity, 
                                                  int statusBarColor, 
                                                  int navigationBarColor,
                                                  boolean lightStatusBar, 
                                                  boolean lightNavigationBar) {
        // 启用 EdgeToEdge
        EdgeToEdge.enable(activity);
        
        Window window = activity.getWindow();
        
        // 设置状态栏颜色
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(statusBarColor);
        }
        
        // 设置导航栏颜色
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            window.setNavigationBarColor(navigationBarColor);
        }
        
        // 设置系统栏图标颜色
        setSystemBarsLight(activity, lightStatusBar, lightNavigationBar);
    }

    public static Point getScreen(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowcore = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowcore.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 assetcore = context.getAssets();
        try (InputStream is = assetcore.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 assetcore = context.getAssets();
            String[] files = assetcore.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);
    }

}

