package tech.starwin.utils.context_utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.UUID;

import tech.starwin.utils.LogUtils;
import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.format_utils.StringFormat;

/**
 * Created by SiKang on 2018/12/10.
 */
public class AppInfoUtils {
    public static final String TAG = "AppInfoUtils_LOG";

    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取AndroidID
     */
    public static String getAndroidID(Context context) {
        String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (TextUtils.isEmpty(android_id)) {
            android_id = PreferencesManager.get().getDeviceUUID();
            if (TextUtils.isEmpty(android_id)) {
                android_id = UUID.randomUUID().toString();
                PreferencesManager.get().saveDeviceUUID(android_id);
            }
        }
        return android_id;
    }


    /**
     * 在SD卡中保存一个设备标识
     */
    public static String saveDeviceUUID() {
        String uuid = UUID.randomUUID().toString();
        try {
            File dir =new File(Environment.getExternalStorageDirectory() + "/star_system/");
            if(!dir.exists()){
                dir.mkdirs();
            }
            File file =new File(dir.getAbsolutePath()+"/device.json");
            if(!file.exists()){
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            fw.flush();
            fw.write(Base64.encodeToString(uuid.getBytes(), Base64.DEFAULT));
            fw.close();
        } catch (IOException e) {
            LogUtils.i(TAG, "getDeviceUUID: " + e.getMessage());
            e.printStackTrace();
        }
        LogUtils.i(TAG, "saveDeviceUUID: " + uuid);
        return uuid;
    }

    public static String getDeviceUUID() {
        try {
            File file =new File(Environment.getExternalStorageDirectory() + "/star_system/"+"/device.json");
            if(!file.exists()){
                return "";
            }
            FileReader fd = new FileReader(file.getAbsolutePath());
            char[] chs = new char[1024];
            while (fd.read(chs) != -1) {
                String str = String.valueOf(chs);
                String uuid = new String(Base64.decode(str.getBytes(), Base64.DEFAULT));
                LogUtils.i(TAG, "getDeviceUUID: " + uuid);
                return uuid;
            }
        } catch (FileNotFoundException e) {
            LogUtils.i(TAG, "getDeviceUUID: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            LogUtils.i(TAG, "getDeviceUUID: " + e.getMessage());
            e.printStackTrace();
        }
        return "";

    }


    /**
     * 判断是否存在某个包且可获取入口
     */
    public static boolean isPackageExist(Context context, String packageName) {
        if (packageName == null || TextUtils.isEmpty(packageName)) {
            return false;
        }
        if (context != null) {
            try {
                if (!(TextUtils.isEmpty(packageName) || context.getPackageManager().getLaunchIntentForPackage(packageName) == null)) {
                    return true;
                }
            } catch (Exception unused) {
                return false;
            }
        }
        return false;
    }

    /**
     * 获取手机IMEI
     *
     * @param context
     * @return
     */
    public static final String getIMEI(Context context) {
        try {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "";
            }
            //实例化TelephonyManager对象
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //获取IMEI号
            String imei = telephonyManager.getDeviceId();
            //在次做个验证，也不是什么时候都能获取到的啊
            if (imei == null) {
                imei = "";
            }
            return imei;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    /**
     * 获取手机IMSI
     */
    public static String getIMSI(Context context) {
        try {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "";
            }
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //获取IMSI号
            String imsi = telephonyManager.getSubscriberId();
            if (null == imsi) {
                imsi = "";
            }
            return imsi;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


//    @SuppressLint("MissingPermission")
//    public static String getPhoneNumber(Context context) {
//        try {
//            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//            if (telephonyManager != null && PermissionsHelper.isGranted(context, Manifest.permission.READ_PHONE_STATE)) {
//                return telephonyManager.getLine1Number();
//            }
//        } catch (Exception e) {
//            return "";
//        }
//        return "";
//    }
//
//    @SuppressLint("MissingPermission")
//    public static String getIMSI(Context context) {
//        try {
//            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//            if (telephonyManager != null && PermissionsHelper.isGranted(context, Manifest.permission.READ_PHONE_STATE)) {
//                String imsi = telephonyManager.getSubscriberId();
//                LogUtils.d("IMSI_INFO",imsi);
//                return imsi;
//            }
//        } catch (Exception e) {
//            return "";
//        }
//        return "";
//    }
//
//
//    @SuppressLint("MissingPermission")
//    public static String getSimSerialNumber(Context context) {
//        try {
//            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//            if (telephonyManager != null && PermissionsHelper.isGranted(context, Manifest.permission.READ_PHONE_STATE)) {
//                return telephonyManager.getSimSerialNumber();
//            }
//        } catch (Exception e) {
//            return "";
//        }
//        return "";
//    }

    /**
     * 判断是否已ROOT
     */
    public static boolean isRoot() {
        try {
            return new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            return false;
        }
    }


}
