package com.tsgame.tsgame_niuniu.util;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import com.google.gson.Gson;
import com.tsgame.tsgame_niuniu.Bean.LianxirenBean;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * 作者：YMI on 2018/4/23 16:35
 * 邮箱：18702631465@163.com
 * QQ:1078561230
 */
public class phoneutil {
    private static final String marshmallowMacAddress = "02:00:00:00:00:00";
    private static final String fileAddressMac = "/sys/class/net/wlan0/address";

    Context context1;
    /**
     * 国际移动用户识别码
     */
    private String IMSI;

    private TelephonyManager telephonyManager;

    public phoneutil(Context context) {
        this.context1 = context;
        telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
    }
   //获取mac
    public String getAdresseMAC() {
        WifiManager wifiMan = (WifiManager) context1.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInf = wifiMan.getConnectionInfo();

        if (wifiInf != null && marshmallowMacAddress.equals(wifiInf.getMacAddress())) {
            String result = null;
            try {
                result = getAdressMacByInterface();
                if (result != null) {
                    return result;
                } else {
                    result = getAddressMacByFile(wifiMan);
                    return result;
                }
            } catch (IOException e) {
                Log.e("MobileAccess", "Erreur lecture propriete Adresse MAC");
            } catch (Exception e) {
                Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
            }
        } else {
            if (wifiInf != null && wifiInf.getMacAddress() != null) {
                return wifiInf.getMacAddress();
            } else {
                return "";
            }
        }
        return marshmallowMacAddress;
    }

    private String getAdressMacByInterface() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (nif.getName().equalsIgnoreCase("wlan0")) {
                    byte[] macBytes = nif.getHardwareAddress();
                    if (macBytes == null) {
                        return "";
                    }

                    StringBuilder res1 = new StringBuilder();
                    for (byte b : macBytes) {
                        res1.append(String.format("%02X:", b));
                    }

                    if (res1.length() > 0) {
                        res1.deleteCharAt(res1.length() - 1);
                    }
                    return res1.toString();
                }
            }

        } catch (Exception e) {
            Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
        }
        return null;
    }

    private static String getAddressMacByFile(WifiManager wifiMan) throws Exception {
        String ret;
        int wifiState = wifiMan.getWifiState();

        wifiMan.setWifiEnabled(true);
        File fl = new File(fileAddressMac);
        FileInputStream fin = new FileInputStream(fl);
        ret = crunchifyGetStringFromStream(fin);
        fin.close();

        boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
        wifiMan.setWifiEnabled(enabled);
        return ret;
    }

    private static String crunchifyGetStringFromStream(InputStream crunchifyStream) throws IOException {
        if (crunchifyStream != null) {
            Writer crunchifyWriter = new StringWriter();

            char[] crunchifyBuffer = new char[2048];
            try {
                Reader crunchifyReader = new BufferedReader(new InputStreamReader(crunchifyStream, "UTF-8"));
                int counter;
                while ((counter = crunchifyReader.read(crunchifyBuffer)) != -1) {
                    crunchifyWriter.write(crunchifyBuffer, 0, counter);
                }
            } finally {
                crunchifyStream.close();
            }
            return crunchifyWriter.toString();
        } else {
            return "No Contents";
        }
    }


    /**
     * 获取手机服务商信息
     */

    public String getProvidersName() {
        String ProvidersName = "N/A";
        return ProvidersName;
//        try {
//            if (ActivityCompat.checkSelfPermission(context1, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                // TODO: Consider calling
//                //    ActivityCompat#requestPermissions
//                // here to request the missing permissions, and then overriding
//                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                //                                          int[] grantResults)
//                // to handle the case where the user grants the permission. See the documentation
//                // for ActivityCompat#requestPermissions for more details.
//                return ProvidersName;
//            }
//
//
//
//
//            String Operator = telephonyManager.getSimOperator();
//            // IOperator 返回SIM卡运营商的单个核细胞数+冶 READ_PHONE_STATE
//            System.out.println(Operator);
//            if (Operator.equals("46000") || Operator.equals("46002") || Operator.equals("46007")) {
//                ProvidersName = "中国移动";
//            } else if (Operator.equals("46001")) {
//                ProvidersName = "中国联通";
//            } else if (Operator.equals("46003")) {
//                ProvidersName = "中国电信";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return ProvidersName;
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机品牌
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机IMEI(需要“android.permission.READ_PHONE_STATE”权限)
     *
     * @return 手机IMEI
     */
    public static String getIMEI(Context ctx) {
        return "";
//        try{
//        TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Activity.TELEPHONY_SERVICE);
//        if (tm != null) {
//            if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                // TODO: Consider calling
//                //    ActivityCompat#requestPermissions
//                // here to request the missing permissions, and then overriding
//                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                //                                          int[] grantResults)
//                // to handle the case where the user grants the permission. See the documentation
//                // for ActivityCompat#requestPermissions for more details.
//                return "";
//            }
//            return tm.getDeviceId();
//        }
//        return null;
//        } catch (Exception e) {
//
//            e.printStackTrace();
//
//            return "";
//        }
    }
    /**
     * 获取手机IMsI(需要“android.permission.READ_PHONE_STATE”权限)
     *
     * @return 手机IMsI
     */
    public static String getIMsI(Context ctx) {
        return "";
//        try{
//
//            TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Activity.TELEPHONY_SERVICE);
//            if (tm != null) {
//                if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                    // TODO: Consider calling
//                    //    ActivityCompat#requestPermissions
//                    // here to request the missing permissions, and then overriding
//                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                    //                                          int[] grantResults)
//                    // to handle the case where the user grants the permission. See the documentation
//                    // for ActivityCompat#requestPermissions for more details.
//                    return "";
//                }
//                return tm.getSubscriberId();
//            }
//            return null;
//        } catch (Exception e) {
//            Log.i("getIMsI","Error");
//            e.printStackTrace();
//
//            return "";
//        }
    }

    /** 获取库Phon表字段 **/
    private static final String[] PHONES_PROJECTION = new String[] {
            Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID,Phone.CONTACT_ID };
    /** 联系人显示名称 **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;

    /** 电话号码 **/
    private static final int PHONES_NUMBER_INDEX = 1;

    /** 头像ID **/
    private static final int PHONES_PHOTO_ID_INDEX = 2;

    /** 联系人的ID **/
    private static final int PHONES_CONTACT_ID_INDEX = 3;


    /** 得到手机通讯录联系人信息 **/
    public static String getPhoneContacts(Context mContext) {
        return "";
//        ContentResolver resolver = mContext.getContentResolver();
//        List<LianxirenBean> list=new ArrayList<>() ;
//        // 获取手机联系人
//        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
//                PHONES_PROJECTION, null, null, null);
//
//        if (phoneCursor != null) {
//            while (phoneCursor.moveToNext()) {
//
//                // 得到手机号码
//                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
//                // 当手机号码为空的或者为空字段 跳过当前循环
//                if (TextUtils.isEmpty(phoneNumber))
//                    continue;
//
//                // 得到联系人名称
//                String contactName = phoneCursor
//                        .getString(PHONES_DISPLAY_NAME_INDEX);
//
//                // 得到联系人ID
//                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
//
//                // 得到联系人头像ID
//                Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
//                LianxirenBean bean=new LianxirenBean();
//                bean.setContactName(contactName);
//                bean.setPhoneNumber(phoneNumber);
//                list.add(bean);
//
//                // 得到联系人头像Bitamp
////                Bitmap contactPhoto = null;
//
////                // photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
////                if (photoid > 0) {
////                    Uri uri = ContentUris.withAppendedId(
////                            ContactsContract.Contacts.CONTENT_URI, contactid);
////                    InputStream input = ContactsContract.Contacts
////                            .openContactPhotoInputStream(resolver, uri);
////                    contactPhoto = BitmapFactory.decodeStream(input);
////                } else {
////                    contactPhoto = BitmapFactory.decodeResource(getResources(),
////                            R.mipmap.ic_launcher);
////                }
//
//
//            }
//
//            phoneCursor.close();
//        }
//        Gson gson=new Gson();
//        String name= gson.toJson(list);
//        System.out.println("------"+name);
//        return name;

    }
}
