package com.common.bluetooth;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.common.bluetooth.bean.AssociateEvent;
import com.common.bluetooth.bean.AssociateSourceEvent;
import com.common.bluetooth.bean.CommonMsg;
import com.common.bluetooth.bean.KeyboardEvent;
import com.common.bluetooth.callback.BLEClientListener;
import com.common.bluetooth.databinding.ActivityMainBinding;
import com.common.bluetooth.view.BtDeviceListAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Set;

/**
 * 蓝牙样例代码
 *
 * @author wangym
 * @since 2021-11-2
 */
public class BtDemoActivity extends AppCompatActivity {
    private static final String TAG = "BtMainActivity";
    /**
     * 启动蓝牙请求码
     */
    private static final int REQUEST_ENABLE_BT = 0;

    /**
     * 获取位置权限
     */
    private static final int PERMISSION_REQUEST_LOCATION = 1;

    private ActivityMainBinding mBinding = null;
    private BtDeviceListAdapter btDeviceListAdapter = null;
    private final ArrayList<BluetoothDevice> bluetoothDevices = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        initView();
        checkBluetooth();
        initData();

        // 设置广播信息过滤
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);//每搜索到一个设备就会发送一个该广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//当全部搜索完后发送该广播
        filter.setPriority(Integer.MAX_VALUE);//设置优先级
        // 注册蓝牙搜索广播接收者，接收并处理搜索结果
        this.registerReceiver(receiver, filter);
    }

    private void initData() {
        bluetoothDevices.clear();
        Set<BluetoothDevice> bondedDevices = BtManager.INSTANCE.getBoundDevices();
        bluetoothDevices.addAll(bondedDevices);

        btDeviceListAdapter = new BtDeviceListAdapter(this, bluetoothDevices);
        LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
        mBinding.bleRv.setLayoutManager(manager);
        mBinding.bleRv.setAdapter(btDeviceListAdapter);

        btDeviceListAdapter.setOnDeviceClickListener(
                index ->
                {
                    BtManager.INSTANCE.connect(bluetoothDevices.get(index).getAddress());
                    BtManager.INSTANCE.setClientListener(new BLEClientListener() {
                        @Override
                        public void onResult(@NonNull CommonMsg result) {
                            Log.e("wangym", "onResult = " + result.getMsg());
                            runOnUiThread(
                                    () -> Toast.makeText(BtDemoActivity.this, result.getMsg(),
                                            Toast.LENGTH_SHORT).show());
                        }

                        @Override
                        public void onNotifyMsgReceive(@NonNull byte[] msg) {
                            Log.e("wangym", "notify = " + new String(msg));
                            runOnUiThread(
                                    () -> Toast.makeText(BtDemoActivity.this, new String(msg),
                                            Toast.LENGTH_SHORT).show());

                        }
                    });
                });
    }

    private void initView() {
        mBinding.searchBle.setOnClickListener(
                l -> BtManager.INSTANCE.searchBtDevice(BtConstants.BLUETOOTH_TYPE.CLASSIC));

        mBinding.sendMsg.setOnClickListener(l -> {
            String value = "*" + mBinding.msgEt.getText().toString() + "#";
            BtManager.INSTANCE.writeMsg(value);
        });

        mBinding.buildBleServer.setOnClickListener(v -> {
            BtManager.INSTANCE.initServer(this, BtConstants.BLUETOOTH_TYPE.BLE);
            BtManager.INSTANCE.setMsgReceiverListener(msg -> runOnUiThread(() -> {
                Object event = BtUtils.INSTANCE.getEventFromSendMsg(msg);
                if (event == null) {
                    mBinding.receiveContent.setText(new String(msg));
                } else if (event instanceof KeyboardEvent) {
                    KeyboardEvent temp = (KeyboardEvent) event;
                    mBinding.receiveContent.setText(new Gson().toJson(temp));
                } else if (event instanceof AssociateEvent) {
                    AssociateEvent temp = (AssociateEvent) event;
                    mBinding.receiveContent.setText(new Gson().toJson(temp));
                } else if (event instanceof AssociateSourceEvent) {
                    AssociateSourceEvent temp = (AssociateSourceEvent) event;
                    mBinding.receiveContent.setText(new Gson().toJson(temp));
                }
            }));
        });
    }

    private void checkBluetooth() {
        BtManager.INSTANCE.initClient(this, BtConstants.BLUETOOTH_TYPE.BLE);
        BtManager.INSTANCE.btPermissionCheck(this, PERMISSION_REQUEST_LOCATION);
    }

    /**
     * 蓝牙扫描事件接收
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "action = " + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                bluetoothDevices.add(device);
                btDeviceListAdapter.notifyDataSetChanged();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {//说明搜索已经完成
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "蓝牙打开成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "蓝牙打开失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST_LOCATION:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    finish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BtManager.INSTANCE.release(this);
    }
}