package com.sheep.jiuyan.samllsheep.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.kfzs.duanduan.view.DialogStorageLow;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;

import java.io.File;
import java.lang.reflect.Method;


/**
 * Created by Dlg on 2015/6/17.
 */
public class G {

    public static int HEIGHT = 1280;//屏幕高
    public static int WIDTH = 720;//屏幕宽
    public static float DENSITY = 2;//屏幕的Density
    public static int DENSITY_DPI = 320;//屏幕的Density
    public static int BAR_HEIGHT = 50;//状态栏高度

    /**
     * @param str
     * @param defaultstr
     * @return 如果str为null或者长度为零，返回defaultstr，否则返回str
     */
    public static final String getString(String str, String defaultstr) {
        return str == null || str.length() < 1 ? defaultstr : str;
    }


    /**
     * 返回像素值
     *
     * @param dp 将转换的dp值
     * @return 返回像素植
     */
    public static int getRealPix(int dp) {
        return (int) (dp * G.DENSITY);
    }


    /**
     * 全局的Toast
     *
     * @param msg      显示的msg，如果为null或者空表示取消显示
     * @param duration 显示的时长
     */
    public static void showToast(String msg, int duration) {
        Toast.makeText(SheepApp.getInstance(), msg, duration).show();
//        if (mToast == null) {
//            mToast = Toast.makeText(SheepApp.getInstance(), msg, duration);
//            mToast.setGravity(Gravity.CENTER, 0, getRealPix(200));//居中靠下
//            if (mToast.getView() instanceof ViewGroup
//                    && ((ViewGroup) mToast.getView()).getChildAt(0) instanceof TextView) {
//                ((TextView) ((ViewGroup) mToast.getView()).getChildAt(0)).setSingleLine(false);
//            }
//        } else if (msg == null || msg.equals(""))
//            mToast.cancel();
//        else {
//            mToast.setText(msg);
//        }
//        mToast.show();
    }

    public static void shortToast(BaseMessage msg){
        if(TextUtils.isEmpty(msg.getMsg())){
            G.shortToast(SheepApp.getInstance().getString(R.string.unknown_error));
        } else {
            G.shortToast(msg.getMsg() + (BuildConfig.DEBUG ? "[" + msg.getCode() + "]" : ""));
        }
    }

    public static void shortToast(String msg){
        Toast t = Toast.makeText(SheepApp.getInstance(), msg, Toast.LENGTH_SHORT);
        t.setGravity(Gravity.CENTER, 0, getRealPix(200));//居中靠下
        t.show();
    }

    public static void showToast(String msg) {
        showToast(msg, Toast.LENGTH_SHORT);
    }
    public static void showToast(int resId) {
        showToast(SheepApp.getInstance().getString(resId), Toast.LENGTH_SHORT);
    }
    public static void showToast(BaseMessage baseMessage) {
        if(TextUtils.isEmpty(baseMessage.getMsg())){
            G.showToast(R.string.unknown_error);
        } else {
            G.showToast(baseMessage.getMsg() + (BuildConfig.DEBUG ? "[" + baseMessage.getCode() + "]" : ""));
        }
    }
    /**
     * 通过反射，获取包含虚拟键的整体屏幕高度
     *
     * @return
     */
    public static int getHasVirtualKey(Activity activity) {
        int dpi = 0;
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            dpi = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }
    /**
     * 获取屏幕尺寸，但是不包括虚拟功能高度
     *
     * @return
     */
    public static int getNoHasVirtualKey(Activity activity) {
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 获取是否存在NavigationBar
     * @param context
     * @return
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }




    /**
     * 获取剩余空间
     *
     * @return
     */
    public static long getFreeSpace() {
        File file = Environment.getDataDirectory();
        StatFs dataFs = new StatFs(file.getPath());
        long sizes;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            sizes = dataFs.getFreeBlocksLong() * dataFs.getBlockSizeLong();
        } else {
            sizes = (long) dataFs.getFreeBlocks() * (long) dataFs.getBlockSize();
        }
        return sizes / ((1024 * 1024));
    }
    public static long getFreeSpaceB() {
        File file = Environment.getDataDirectory();
        StatFs dataFs = new StatFs(file.getPath());
        long sizes;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            sizes = dataFs.getFreeBlocksLong() * dataFs.getBlockSizeLong();
        } else {
            sizes = (long) dataFs.getFreeBlocks() * (long) dataFs.getBlockSize();
        }
        return sizes ;
    }


    public static int getPercent(long allcount, long calcount) {
        int percent = 0;
        if (allcount > 0 && calcount <= allcount) {
            percent = 100 - (int) (calcount / (float) allcount * 100.0f);
            if (percent < 0) {
                percent = 0;
            }
        }
        return percent;
    }

    /**
     * 判断sd卡是否可用
     * return true 可用  false 不可用
     */
    public static boolean isSDCardEnable(){
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 获取SD卡剩余空间
     *
     * @return SD卡剩余空间
     */
    public static long getSdkFreeSpace(){
        try{
            if(!isSDCardEnable()){
                return 0;
            }//获取SDCard根目录
            File path = Environment.getExternalStorageDirectory();
            StatFs statFs = new StatFs(path.getPath());
            long blockSize, availableBlocks;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                availableBlocks = statFs.getAvailableBlocksLong();
                blockSize = statFs.getBlockSizeLong();
            } else {
                availableBlocks = statFs.getAvailableBlocks();
                blockSize = statFs.getBlockSize();
            }

            return availableBlocks * blockSize;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 判断文件空间大小
     */
    public static void showInstallToast(Context context, File file){
        try{
            if (0 <= file.length() && (
                    file.length() > getFreeSpaceB() / 2
                            && file.length() > getSdkFreeSpace() / 2
            )) {
                DialogStorageLow.showDialog(null);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
