package tech.starwin.utils.context_utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;

import com.common.bean.DeviceInfoBean;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Locale;
import java.util.TimeZone;

import tech.starwin.BuildConfig;

/**
 * Created by SiKang on 2019-11-15.
 */
public class DeviceUtils {
    private DeviceInfoBean deviceInfoBean;
    private static DeviceUtils deviceUtils = new DeviceUtils();


    public static DeviceUtils getInstance() {
        return deviceUtils;
    }

    DeviceUtils() {
        deviceInfoBean = new DeviceInfoBean();
    }

    /**
     * 如果APP更改了语言，需要在更改之前初始化
     */
    public void init(Context context) {
        deviceInfoBean.setScreenWidth(context.getResources().getDisplayMetrics().widthPixels);
        deviceInfoBean.setScreenHeight(context.getResources().getDisplayMetrics().heightPixels);
        deviceInfoBean.setRoot(AppInfoUtils.isRoot());
        deviceInfoBean.setAndroidId(Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));

        deviceInfoBean.setLocal(Locale.getDefault());
        deviceInfoBean.setTimeZone(TimeZone.getDefault());

        long[] ramInfo = getRAMInfo(context);
        deviceInfoBean.setTotalMemory(ramInfo[0]);
        deviceInfoBean.setFreeMemory(ramInfo[1]);

        long[] romInfo = getROMInfo();
        deviceInfoBean.setDiskSpace(romInfo[0]);
        deviceInfoBean.setDiskFreeSpace(romInfo[1]);

        deviceInfoBean.setAppSign(BuildConfig.KEYSTORE_SIGN);
        deviceInfoBean.setBaseBandVersion(getBaseBandVersion());
        deviceInfoBean.setBattery(getBattery(context));
        deviceInfoBean.setBluetooth(Settings.Secure.getString(context.getContentResolver(), "bluetooth_address"));
        deviceInfoBean.setCameraNum(Camera.getNumberOfCameras());
        deviceInfoBean.setDebug((Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ADB_ENABLED, 0) > 0));
        deviceInfoBean.setSimulator(isSimulator());
        deviceInfoBean.setKernelVersion(getKernelVersion());
        deviceInfoBean.setMacAddress(getMacAddress());
        deviceInfoBean.setUpTime(SystemClock.elapsedRealtime());

//        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//        deviceInfoBean.setWifiSsid(wifi.getConnectionInfo().getSSID());
//        deviceInfoBean.setWifiBssid(wifi.getConnectionInfo().getBSSID());
//        deviceInfoBean.setWifiRssi(wifi.getConnectionInfo().getRssi());
    }

    public DeviceInfoBean getDeviceInfo() {
        return deviceInfoBean;
    }

    private long[] getRAMInfo(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        manager.getMemoryInfo(info);
        return new long[]{info.totalMem, info.availMem};
    }

    private long[] getROMInfo() {
        final StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
        long totalCounts = statFs.getBlockCountLong();//总共的block数
        long availableCounts = statFs.getAvailableBlocksLong(); //获取可用的block数
        long size = statFs.getBlockSizeLong(); //每格所占的大小，一般是4KB==
        long availROMSize = availableCounts * size;//可用内部存储大小
        long totalROMSize = totalCounts * size; //内部存储总大小
        return new long[]{totalROMSize, availROMSize};

    }

    public String getBaseBandVersion() {
        String version = "";
        try {
            @SuppressLint("PrivateApi") Class cl = Class.forName("android.os.SystemProperties");
            Object invoker = cl.newInstance();
            //noinspection unchecked
            Method m = cl.getMethod("get", String.class, String.class);
            Object result = m.invoke(invoker, "gsm.version.baseband", "no message");
            version = (String) result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        String radioVersion = Build.getRadioVersion();
        version = TextUtils.isEmpty(version) ? radioVersion : version;
        return version == null ? "" : version;
    }

    /**
     * 电池信息
     *
     * @param context
     * @return
     */
    public int getBattery(Context context) {
        //API >= 21 (5.0，L)
        BatteryManager manager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);

        int batteryCurrentCap = 0;///当前电量百分比
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            batteryCurrentCap = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = new ContextWrapper(context).registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            if (intent != null) {
                batteryCurrentCap = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            }
        }
        return batteryCurrentCap;
    }


    /*
     *根据CPU是否为电脑来判断是否为模拟器
     *返回:true 为模拟器
     */
    public boolean isSimulator() {
        try {
            String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
            ProcessBuilder cmd = new ProcessBuilder(args);

            Process process = cmd.start();
            StringBuffer sb = new StringBuffer();
            String readLine = "";
            BufferedReader responseReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
            while ((readLine = responseReader.readLine()) != null) {
                sb.append(readLine);
            }
            responseReader.close();
            String cpuInfo = sb.toString().toLowerCase();
            if ((cpuInfo.contains("intel") || cpuInfo.contains("amd"))) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public String getKernelVersion() {
        Process process;
        String mLinuxKernal = null;
        try {
            process = Runtime.getRuntime().exec("cat /proc/version");
            if (process != null) {
                InputStream outs = process.getInputStream();
                InputStreamReader isrout = new InputStreamReader(outs);
                BufferedReader brout = new BufferedReader(isrout, 8 * 1024);

                StringBuilder result = new StringBuilder();
                String line;
                // get the whole standard output string
                try {
                    while ((line = brout.readLine()) != null) {
                        result.append(line);
                        // result += "\n";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (!"".equals(result.toString())) {
                    String keyword = "version ";
                    int index = result.indexOf(keyword);
                    line = result.substring(index + keyword.length());
                    index = line.indexOf(" ");
                    mLinuxKernal = line.substring(0, index);
                }
            }
            mLinuxKernal = TextUtils.isEmpty(mLinuxKernal) ? System.getProperty("os.version") : mLinuxKernal;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mLinuxKernal == null ? "" : mLinuxKernal;
    }


    /**
     * 获取mac地址
     *
     * @return
     */
    public String getMacAddress() {
        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "";
            }
            byte[] addr = networkInterface.getHardwareAddress();
            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return macAddress == null ? "" : macAddress;
    }
}
