package com.tofly.ghrq_route.common.util;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import java.lang.reflect.Method;

/**
 * Created by lihualong on 2017/11/6.
 */

public class ScreenUtils {
    /**
     * dip 转px
     *
     * @param context
     * @param dip
     * @return
     */
    static public int dipToPx(Context context, int dip) {
        return (int) (dip * getScreenDensity(context) + 0.5f);
    }

    /**
     * 获取屏幕密度
     *
     * @param context
     * @return
     */

    public static float getScreenDensity(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                    .getMetrics(dm);
            return dm.density;
        } catch (Exception e) {
            return DisplayMetrics.DENSITY_DEFAULT;
        }
    }

    /**
     * 获取整个窗口的高度（包含虚拟按键的高度）
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager service = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = service.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        int heightPixels = 0;
        try {
            Class<?> aClass = Class.forName("android.view.Display");
            Method getRealMetrics = aClass.getMethod("getRealMetrics", DisplayMetrics.class);
            getRealMetrics.invoke(display, displayMetrics);
            heightPixels = displayMetrics.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return heightPixels;
    }

    /**
     * 获取整个窗口的高度（包含虚拟按键的高度）
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager service = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = service.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        int heightPixels = 0;
        try {
            Class<?> aClass = Class.forName("android.view.Display");
            Method getRealMetrics = aClass.getMethod("getRealMetrics", DisplayMetrics.class);
            getRealMetrics.invoke(display, displayMetrics);
            heightPixels = displayMetrics.widthPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return heightPixels;
    }

    /**
     * 获取窗口的高度，不包含虚拟按键的高度
     *
     * @param context
     * @return
     */
    public static int getWindowHeight(Context context) {
        WindowManager service = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        service.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }
}
