package cgmblelib.receiver;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;

import cgmblelib.ble.gattcallback.BleGattCallback;
import cgmblelib.ble.gattcallback.ManageGattCallback;
import cgmblelib.ble.reconnectManagament.ReconnectManagement;
import cgmblelib.ble.scancallback.ManageScanCallback;
import cgmblelib.custom.livedata.ManagementLiveData;
import cgmblelib.custom.livedata.connect.EnumConnect;
import cgmblelib.custom.livedata.scan.EnumScan;
import cgmblelib.database.repository.RepositoryDevice;
import cgmblelib.utils.MyLog;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 事件接受类,接受所有有需要的广播类型进行处理
 *
 * @author minyuchun
 */
public class BleServiceReceiver extends BroadcastReceiver {
    /**
     * 广播订阅
     *
     * @param context 上下文
     */
    public void initReceiver(Context context) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        context.registerReceiver(this, intentFilter);
    }

    /**
     * 取消订阅
     *
     * @param context 上下文
     */
    public void unregisterReceiver(Context context) {
        try {
            context.unregisterReceiver(this);
            dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null) {
            if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                //TODO 广播接收到 - 蓝牙状态改变
                bluetoothChange(context, intent);
            }
        }
    }

    private Disposable mDisposable;

    private void connectChange(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network network = manager.getActiveNetwork();
        NetworkCapabilities caps = manager.getNetworkCapabilities(network);
        if (network != null &&  caps!= null && caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
            mDisposable = Observable.just(context)
                    .subscribeOn(Schedulers.io())
                    .map(contexts -> RepositoryDevice.getInstance(contexts).getLatestDeviceIoThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(pocDevice -> {
                        if (pocDevice != null && pocDevice.isBoundButDisConnect()) {
                            ReconnectManagement.getInstance().reconnect(ReconnectManagement.ReconnectState.STATE_RECONNECT);
                            ManagementLiveData.getInstance().updateOperationConnect(EnumConnect.CONNECT_ONLINE_RECONNECT);
                        }
                    }, throwable -> {
                        dispose();
                    });
        } else {
            BleGattCallback.getInstance().disConnectGatt();
        }
    }

    /**
     * 取消任务
     */
    public void dispose() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            MyLog.i("dispose cancel");
            mDisposable.dispose();
        }
    }

    /**
     * 系统蓝牙发生变化
     *
     * @param context 上下文
     * @param intent  广播intent
     */
    private void bluetoothChange(Context context, Intent intent) {
        try {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            switch (state) {
                case BluetoothAdapter.STATE_ON:
                    ManagementLiveData.getInstance().updateOperationScan(EnumScan.SCAN_ERROR_BLUETOOTH_ON);
                    ManageScanCallback.getInstance().bluetoothChange(true);
                    ManageGattCallback.getInstance().bluetoothChange(true);
                    break;
                case BluetoothAdapter.STATE_OFF:
                    ManagementLiveData.getInstance().updateOperationScan(EnumScan.SCAN_ERROR_BLUETOOTH_OFF);
                    ManageScanCallback.getInstance().bluetoothChange(false);
                    ManageGattCallback.getInstance().bluetoothChange(false);
                    ReconnectManagement.getInstance().stopReconnect();
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
