package com.dskj.daikuan.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import java.io.File;


public final class DeviceUtil {

    public static int SCREEN_WIDTH;
    public static int SCREEN_HEIGHT;

    public static float DENSITY;
    public static float DENSITY_SCALE;
    public static int DENSITY_DPI;

    public static void init(Context context) {
        if (null == context) return;
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        SCREEN_WIDTH = displayMetrics.widthPixels;
        SCREEN_HEIGHT = displayMetrics.heightPixels;
        DENSITY = displayMetrics.density;
        DENSITY_SCALE = displayMetrics.scaledDensity;
        DENSITY_DPI = displayMetrics.densityDpi;
    }

    public static int dip2px(float dip) {
        return (int) (dip * DENSITY + 0.5F);
    }

    public static boolean isStorageEnough(Context context, long minSize) {
        try {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.toString());
            long blocksize = stat.getBlockSizeLong();
            long availbleblocks = stat.getAvailableBlocksLong();
            long avilableSize = availbleblocks * blocksize;
            return avilableSize >= minSize;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }



    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     * @param context   上下文
     * @param pxValue   px值
     * @return  dp值
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取当前的屏幕尺寸
     *
     * @param context {@link Context}
     * @return 屏幕尺寸
     */
    public static int[] getScreenSize(Context context) {
        int[] size = new int[2];

        WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);

        size[0] = metrics.widthPixels;
        size[1] = metrics.heightPixels;
        return size;
    }
}
