package com.siwei.recyclebox.ui.main;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.databinding.ViewDataBinding;
import android.net.TrafficStats;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.siwei.recyclebox.BR;
import com.siwei.recyclebox.R;
import com.siwei.recyclebox.service.MyService;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.util.Timer;
import java.util.TimerTask;

import me.goldze.mvvmhabit.base.BaseActivity;

import static java.nio.file.Files.newBufferedReader;


public class MainActivity extends BaseActivity<ViewDataBinding,MainViewModel> {
    TimerTask task1;
    Timer timer=new Timer();
    TelephonyManager telephonyManager ;
    private PhoneStatListener phoneStatListener;
    private static final String TAG = "MainActivity";


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Log.i("uuid","="+getMacAddress());
//        getNetSpeed(getApplicationContext());//获取网速
//        listenerSignal(getApplication());//获取信号强度
//        task1=new TimerTask() {
//            @Override
//            public void run() {
//                try {
//                    getNetQuelity();//获取ping ip 的丢包率和延迟
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        };
//        timer.schedule(task1,1000,4000);
    }

    //页面接收的参数方法
    @Override
    public void initParam() {
        super.initParam();
        Intent service = new Intent(getApplication(), MyService.class);
        getApplication().startService(service);
        getApplication().bindService(new Intent(MainActivity.this,MyService.class),mConnection, Service.BIND_AUTO_CREATE);

    }

    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;
    /**
     * 得到网络速度
     * @param context
     * @return
     */
    public String getNetSpeed(Context context) {
        Log.i("getNetSpeed","1----------------------------------------------------------");
        String netSpeed = "0 kb/s";
        long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid)==
                TrafficStats.UNSUPPORTED ? 0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB;
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;
        netSpeed  = String.valueOf(speed) + " kb/s";
        Log.i("getNetSpeed","网速:"+netSpeed);
        Log.i("getNetSpeed","2----------------------------------------------------------");
        return  netSpeed;

    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void getNetQuelity() throws IOException {
        String lost;
        String delay;
        //a13H8L6bDyf.iot-as-mqtt.cn-huadong2.aliyuncs.com:1883
        Process p = Runtime.getRuntime().exec("ping -c 4 " + "a13H8L6bDyf.iot-as-mqtt.cn-shanghai.aliyuncs.com");
        BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String str = "";
        while((str=buf.readLine())!=null){
            if(str.contains("packet loss")){
                int i= str.indexOf("received");
                int j= str.indexOf("%");
                System.out.println("丢包率:"+str.substring(i+10, j+1));
//					System.out.println("丢包率:"+str.substring(j-3, j+1));
                lost = str.substring(i+10, j+1);
                Log.i(TAG,"getNetQuelity--------------------"+lost);
            }
            if(str.contains("avg")){
                int i=str.indexOf("/", 20);
                int j=str.indexOf(".", i);
                System.out.println("延迟:"+str.substring(i+1, j));
                delay =str.substring(i+1, j);
                delay = delay+"ms";
                Log.i(TAG,"getNetQuelity--------------------"+delay);
            }
        }
    }
    /**
     * 监听网络强度
     *
     * @param context
     */
    public void listenerSignal(Context context) {
        Log.i("listenerSignal","1----------------------------------------------------------");

        //获取一个电话管理类
        telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        phoneStatListener = new PhoneStatListener();

        //通过 listen 方法来侦听电话信息的改变，这里用来侦听网络信号的强度变化，具体还能侦听什么需要看 PhoneStateListener 类的源码
        telephonyManager.listen(phoneStatListener, PhoneStatListener.LISTEN_SIGNAL_STRENGTHS);
        Log.i("listenerSignal","2----------------------------------------------------------");
    }
    private class PhoneStatListener extends PhoneStateListener {
        private int mSignalStrength=0;
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            Log.i("PhoneStatListener","信号:"+mSignalStrength);
            //获取信号强度变化
            super.onSignalStrengthsChanged(signalStrength);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mSignalStrength = signalStrength.getLevel();
                return;
            }
            mSignalStrength = signalStrength.getGsmSignalStrength();
            Log.i("PhoneStatListener","信号:"+mSignalStrength);
        }
    }

//    public String getMacAddress() {
//        //获取 uuid
//        String macAddress = null;
//        WifiManager wifiManager =
//                (WifiManager)getApplication().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        WifiInfo info = (null == wifiManager ? null : wifiManager.getConnectionInfo());
//        if (!wifiManager.isWifiEnabled()){
//            //必须先打开，才能获取到MAC地址
//            wifiManager.setWifiEnabled(true);
//            wifiManager.setWifiEnabled(false);
//        }
//        if (null != info) {
//            macAddress = info.getMacAddress();
//        }
//        return macAddress;
//    }

    MyService mService=null;
    private ServiceConnection mConnection = new ServiceConnection() {


        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }

        @Override
         public void onServiceConnected(ComponentName name, IBinder service) {
                         // 获取服务上的IBinder对象，调用IBinder对象中定义的自定义方法，获取Service对象
            MyService.LocalBinder binder=(MyService.LocalBinder)service;
                       mService=binder.getService();
                    }
    };



    //页面数据初始化方法。
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initData() {
//        viewModel.btnClick.onClick();
//        viewModel.btnText.set("");
        openBlueTooth();
        viewModel.registerAliIoTListener();
//        viewModel.startJobScheduler();
//        viewModel.repeatTask();
        Log.i("repeatTask","*****************************************");
        viewModel.startBLEServer();
        if(!isIgnoringBatteryOptimizations()){
            requestIgnoreBatteryOptimizations();
        }
        viewModel.netWorkInfo();
//        viewModel.openWeight();
//        System.out.println("serialPortUtil.readControllerStatus:"+ SerialPortUtil.getInstance().readRelayControllerStatus());
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean isIgnoringBatteryOptimizations() {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
            Log.i("白名单","已经添加白名单");
        }
        return isIgnoring;
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestIgnoreBatteryOptimizations() {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            Log.i("白名单","申请添加白名单");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void openBlueTooth(){
//      打开蓝牙（提示对话框）
//        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
//        startActivity(discoverableIntent);

//        打开蓝牙（静默，无提示）
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.enable();//需要BLUETOOTH_ADMIN权限

    }
    public void closeBlueTooth(){
//      关闭蓝牙
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.disable();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.requestFilePermissions.observe(this, aBoolean -> {
            //请求读写文件的权限。
            Log.d(TAG,"请求文件读写的权限");
            /*RxPermissions permissions = new RxPermissions(this);
            Disposable disposable =permissions.request(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE})
                .subscribe(granted->{
                    if(granted){
                        Log.d(TAG,"文件读写权限以获取！");
                        viewModel.otaListener();
                    }else{
                        ToastUtils.showShortSafe("请同意文件读写权限。");

                    }
            });*/

        });
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewModel.stopBleServer();
        viewModel.unRegisterIoTListener();
        getApplication().unbindService(mConnection);
        mService=null;
        viewModel.closePort();

//        Log.e("MainActivity.","unregisterIoTListener!!!");
//        Intent mStartActivity = new Intent(getApplication(),MainActivity.class);
//        int mPendingIntentId = 123456;
//        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplication(), mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
//        AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
//        System.exit(0);

    }

    @Override
    protected void onStop() {
        super.onStop();

        getApplication().unbindService(mConnection);
        mService=null;
//        viewModel.stopBleServer();
//        viewModel.unRegisterIoTListener();
//        Log.e("MainActivity.","unregisterIoTListener!!!");
//        Intent mStartActivity = new Intent(getApplication(),MainActivity.class);
//        int mPendingIntentId = 123456;
//        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplication(), mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
//        AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
//        System.exit(0);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewModal;
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        System.out.println("onPointerCaptureChanged:"+hasCapture);
    }

    @Override
    public MainViewModel initViewModel() {
        //View持有ViewModel的引用，如果没有特殊业务处理，这个方法可以不重写
        return super.initViewModel();
    }
}
