package com.baidu.rtc.sample.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.baidu.rtc.sample.data.ContextConstant;

import java.lang.reflect.Method;

/**
 * ScreenUtil
 *
 * @author zhoujunjiang
 * @version V1.0
 * @since 2018/11/30
 */
public class ScreenUtil {
    public static boolean sDeviceDataInit = false;
    private static float sDisplayMetricsDensity;
    static int sDisplayMetricsWidthPixels;
    static int sDisplayMetricsHeightPixels;
    private static int realScreenHeight = 0;
    private static float sDisplayRate = 0.f;

    public static void initDeviceData() {
        DisplayMetrics metric = new DisplayMetrics();
        WindowManager manager = (WindowManager) ContextConstant.getContext().getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(metric);
        int orientation = manager.getDefaultDisplay().getOrientation();
        if (orientation == Surface.ROTATION_90 || orientation == Surface.ROTATION_270) {
            sDisplayMetricsWidthPixels = metric.heightPixels; // 屏幕宽度（像素）
            sDisplayMetricsHeightPixels = metric.widthPixels; // 屏幕高度（像素）
        } else {
            sDisplayMetricsWidthPixels = metric.widthPixels; // 屏幕宽度（像素）
            sDisplayMetricsHeightPixels = metric.heightPixels; // 屏幕高度（像素）
        }
        sDisplayMetricsDensity = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
        sDeviceDataInit = true;
    }

    public static int getEquipmentWidth() {
        if (!sDeviceDataInit) {
            initDeviceData();
        }

        return sDisplayMetricsWidthPixels;
    }

    public static int getEquipmentHeight() {
        if (!sDeviceDataInit) {
            initDeviceData();
        }

        return sDisplayMetricsHeightPixels;
    }

    public static float getEquipmentDensity() {
        if (!sDeviceDataInit) {
            initDeviceData();
        }

        return sDisplayMetricsDensity;
    }

    public static DisplayMetrics getScreenSize(Activity activity) {
        DisplayMetrics result = null;
        try {
            result = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static int getRealScreenOrientation() {
        int[] xy = getScreenDimensions();
        int orientation = ContextConstant.getContext().getResources().getConfiguration().orientation;
        if (orientation != Configuration.ORIENTATION_LANDSCAPE && xy[0] > xy[1]) {
            orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
        return orientation;
    }

    public static int[] getScreenDimensions() {
        int[] dimensions = new int[2];
        Context ap = ContextConstant.getContext();
        Display display = ((WindowManager) ap.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        dimensions[0] = display.getWidth();
        dimensions[1] = display.getHeight();
        return dimensions;
    }

    /**
     * 获取虚拟键高度(无论是否隐藏)
     */
    public static int getNavigationBarHeight() {
        int result = 0;
        int resourceId = ContextConstant.getContext().getResources().getIdentifier("navigation_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = ContextConstant.getContext().getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 虚拟按键是否打开
     */
    public static boolean isNavigationBarShown(Activity activity) {
        View view = activity.findViewById(android.R.id.navigationBarBackground);
        if (view == null) {
            return false;
        }
        int visible = view.getVisibility();
        if (visible == View.GONE || visible == View.INVISIBLE) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 不依赖Context 拿到屏幕的高度
     */
    public static int getScreenHeight() {
        return getEquipmentHeight();
    }

    /**
     * 获取屏幕原始高度，包括状态栏和虚拟按键，单位 px
     */
    public static int getRealScreenHeight() {
        if (realScreenHeight == 0) {
            int height = 0;
            try {
                WindowManager windowManager = (WindowManager) ContextConstant.getContext()
                        .getSystemService(Context.WINDOW_SERVICE);
                Display display = windowManager.getDefaultDisplay();
                DisplayMetrics displayMetrics = new DisplayMetrics();
                Class c = Class.forName("android.view.Display");
                Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
                method.invoke(display, displayMetrics);
                height = displayMetrics.heightPixels;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (height == 0) {
                height = getScreenHeight();
            }
            realScreenHeight = height;
        }
        return realScreenHeight;
    }

    /**
     * 不依赖Context 拿到屏幕的宽度
     */
    public static int getScreenWidth() {
        return getEquipmentWidth();
    }

    public static int dip2px(float dipValue) {
        if (!sDeviceDataInit) {
            initDeviceData();
        }
        return (int) (dipValue * sDisplayMetricsDensity + 0.5f);
    }

    public static boolean containsNotch() {
        return containsNotchInVivo();
    }

    private static final int NOTCH_IN_SCREEN_VIVO = 0x00000020;
    private static final int ROUNDED_IN_SCREEN_VIVO = 0x00000008;

    /**
     * vivo手机是否有刘海
     */
    private static boolean containsNotchInVivo() {
        boolean ret = false;
        try {
            ClassLoader cl = ContextConstant.getContext().getClassLoader();
            Class ftFeature = cl.loadClass("android.util.FtFeature");
            Method get = ftFeature.getMethod("isFeatureSupport", int.class);
            ret = (boolean) get.invoke(ftFeature, NOTCH_IN_SCREEN_VIVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    private static Rect getViewRect(Activity activity) {
        if (activity == null) {
            return null;
        }
        View view = ((ViewGroup) activity.getWindow().getDecorView()).getChildAt(0);
        if (view != null) {
            Rect rect = new Rect();
            view.getGlobalVisibleRect(rect);
            return rect;
        } else {
            return null;
        }
    }

    private static float getRate(Rect rect) {
        int screenWidth = ScreenUtil.getScreenWidth();
        int screenHeight = ScreenUtil.getScreenHeight();
        int realHeight = ScreenUtil.getRealScreenHeight();
        if (rect != null && rect.width() == screenWidth) {
            if (rect.height() <= realHeight && rect.height() >= screenHeight) {
                screenHeight = rect.height();
            }
        }
        return screenWidth * 1f / screenHeight;
    }

    public static void clearDisplayRate() {
        sDisplayRate = 0f;
    }

    public interface OnDisplayRectListener {
        void onRate(float rate);
    }
}
