package com.xplora.xpsettings.Activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.xplora.xpsettings.Adapter.BluetoothDevicesAdapter;
import com.xplora.xpsettings.Model.BluetoothModel;
import com.xplora.xpsettings.R;
import com.xplora.xpsettings.Utils.Constant;

import java.util.ArrayList;
import java.util.List;

public class BluetoothActivity extends BaseActivity {
    private final List<BluetoothModel> mDataList = new ArrayList<>();
    private BluetoothDevicesAdapter mDevicesAdapter;
    android.bluetooth.BluetoothAdapter bluetoothAdapter;
    ListView listView;
    private static final int REQUEST_LOGIN = 0;
    private static final int REQUEST_CONTROL = 1;
    private List<String> mPermissionList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        initPermission();
        //initBluetooth();

//        initData();
//        initView();
    }

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 版本大于等于 Android12 时
            // 只包括蓝牙这部分的权限，其余的需要什么权限自己添加
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        } else {
            // Android 版本小于 Android12 及以下版本
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (mPermissionList.size() > 0) {
            ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), 1001);
        }
    }

    private void initBluetooth() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mBluetoothReceiver, filter);

        //初始化蓝牙适配器
        BluetoothManager bluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
        //初始化蓝牙
        bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter == null) {
            //设备不支持蓝牙
            return;
        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != 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;
        }
        bluetoothAdapter.startDiscovery();
        boolean isOpen = bluetoothAdapter.isEnabled();
        int i = 0;
        i++;
    }

    private void initBluetooth11() {
        //初始化蓝牙适配器
        BluetoothManager bluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
        //初始化蓝牙
        bluetoothAdapter = bluetoothManager.getAdapter();
        //初始化List
        List mBlueList = new ArrayList<>();
        //实例化蓝牙回调

        BluetoothAdapter.LeScanCallback mLesanCall = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                //返回三个对象 分类别是 蓝牙对象 蓝牙信号强度 以及蓝牙的广播包
                if (!mBlueList.contains(bluetoothDevice)) {
                    mBlueList.add(bluetoothDevice);
                }
            }
        };
    }

    // 扫描蓝牙
    @RequiresApi(api = Build.VERSION_CODES.S)
    private void scanBle() {
        // 初始化蓝牙适配器
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager == null) {
            return;
        }
        bluetoothAdapter = bluetoothManager.getAdapter();

        // 打开蓝牙
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
//            Intent enable = new Intent(BluetoothDevicesAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(enable, 1);
        } else {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != 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.

                String[] permission = {
                        Manifest.permission.BLUETOOTH,
                        Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.BLUETOOTH_ADVERTISE,
                        Manifest.permission.BLUETOOTH_CONNECT,
                        Manifest.permission.BLUETOOTH_PRIVILEGED,
                        Manifest.permission.BLUETOOTH_SCAN,
                };
                ActivityCompat.requestPermissions(this, permission, 0);
                return;
            }
            bluetoothAdapter.startLeScan(oldBtsc);
            // 设置扫描时间
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    bluetoothAdapter.stopLeScan(oldBtsc);
                }
            }, 8000);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        }

        initBluetooth();
    }

    private BluetoothAdapter.LeScanCallback oldBtsc = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            //mDataList.add(device.getAddress() + "");
            mDevicesAdapter.notifyDataSetChanged();
        }
    };

    private void initData() {
        String[] stringList = getResources().getStringArray(R.array.connections_title_array);

        BluetoothModel switchModel = new BluetoothModel();
        switchModel.title = stringList[0];
        switchModel.cellType = Constant.CellType.SWITCH;
        mDataList.add(switchModel);

        BluetoothModel refreshModel = new BluetoothModel();
        refreshModel.title = getResources().getString(R.string.available_devices);
        refreshModel.cellType = Constant.CellType.REFRESH;
        mDataList.add(refreshModel);

        for (int i = 0; i < 10; i++) {
            BluetoothModel model = new BluetoothModel();
            model.title = "aaaa";
            model.cellType = Constant.CellType.ICON_TITLE_SUBTITLE;
            mDataList.add(model);
        }
    }

    private void initView() {
        mDevicesAdapter = new BluetoothDevicesAdapter(BluetoothActivity.this, 0, mDataList, handler);
        listView = findViewById(R.id.activity_listview);
        listView.setAdapter(mDevicesAdapter);

        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            BluetoothModel model = (BluetoothModel) adapterView.getAdapter().getItem(i);
            if (i != 0) {
//                if (model.status == WifiModel.STATUS.LOCKED) {
//                    Intent intent = new Intent(BluetoothActivity.this, WifiLoginActivity.class);
//                    intent.putExtra("ssid", model.title);
//                    intent.putExtra("bssid", model.BSSID);
//                    startActivityForResult(intent, REQUEST_LOGIN);
//                } else if (model.status == WifiModel.STATUS.OPEN) {
//                    //connect(model.title, model.BSSID, "");
//                } else if (model.status == WifiModel.STATUS.SAVED || model.status == WifiModel.STATUS.CONNECTED) {
//                    Intent intent = new Intent(BluetoothActivity.this, WiFiControlActivity.class);
//                    intent.putExtra("ssid", model.title);
//                    intent.putExtra("bssid", model.BSSID);
//                    intent.putExtra("status", model.status.ordinal());
//                    startActivityForResult(intent, REQUEST_CONTROL);
//                }
            }
        });
    }

    Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
                //Log.d("BlueToothTestActivity", "ACTION_FOUND......");
                if (device.getName() != null && device.getName().length() > 0) {
                    BluetoothModel model = new BluetoothModel();
                    model.name = device.getName();
                    model.device = device;
                    //mViewAdapter.addItem(info);
                    mDevicesAdapter.notifyDataSetChanged();
                }
            } else if (android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(intent.getAction())) {
                //mFindLoadingBar.setVisibility(View.VISIBLE);
                //Log.d("BlueToothTestActivity", "STARTED......");
                int i = 0;
                i++;
            } else if (android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {
                //mFindLoadingBar.setVisibility(View.GONE);
                //Log.d("BlueToothTestActivity", "FINISHED......");
                int i = 0;
                i++;
            } else if(android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())){
                int state = intent.getIntExtra(android.bluetooth.BluetoothAdapter.EXTRA_STATE, -1);
                switch (state) {
                    case android.bluetooth.BluetoothAdapter.STATE_TURNING_ON:
                        //Log.i(TAG, "BluetoothAdapter is turning checkbox_on.");
                        break;
                    case android.bluetooth.BluetoothAdapter.STATE_ON:
                        //updataPaired();
                        break;
                    case android.bluetooth.BluetoothAdapter.STATE_TURNING_OFF:
                        //Log.i(TAG, "BluetoothAdapter is turning checkbox_off.");
                        break;
                    case android.bluetooth.BluetoothAdapter.STATE_OFF:
                        //Log.i(TAG, "BluetoothAdapter is checkbox_off.");
                        break;
                }
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_BONDING:
                        //Log.d("BlueToothTestActivity", "正在配对......");
                        mDevicesAdapter.notifyDataSetChanged();
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        //Log.d("BlueToothTestActivity", "完成配对");
                        mDevicesAdapter.notifyDataSetChanged();
                        break;
                    case BluetoothDevice.BOND_NONE:
                        //Log.d("BlueToothTestActivity", "取消配对");
                        mDevicesAdapter.notifyDataSetChanged();
                    default:
                        break;
                }
            }
        }
    };
}
