package xn.hxp.weidith.ble;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialog;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.data.BleScanState;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.kongzue.dialogx.dialogs.PopTip;

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

import xn.hxp.databinding.DialogBleSelectorBinding;

public class BleSelectorDialog extends AppCompatDialog {
    private Context context;
    private DialogBleSelectorBinding binding;
    private List<BleDevice> deviceList = new ArrayList<>();
    private BleScanAdapter bleScanAdapter;

    public BleSelectorDialog(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DialogBleSelectorBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        if (BleManager.getInstance().isBlueEnable()) {
            BleManager.getInstance().disconnectAllDevice();
        } else {
            BleManager.getInstance().enableBluetooth();
        }
        bleScanAdapter = new BleScanAdapter(context, deviceList);
        binding.bleLV.setAdapter(bleScanAdapter);
        binding.bleLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SPUtils.getInstance().put("bleMac", deviceList.get(position).getMac());
                SPUtils.getInstance().put("bleName", deviceList.get(position).getName());
                SPUtils.getInstance().put("bleKey", deviceList.get(position).getKey());
                dismiss();
            }
        });
        binding.ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.ok.setVisibility(View.GONE);
                binding.cancel.setVisibility(View.VISIBLE);
                binding.bleLV.setVisibility(View.VISIBLE);
                binding.loadingLAV.setVisibility(View.VISIBLE);
                binding.loadingLAV.playAnimation();
                BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                        .setScanTimeOut(5000)
                        .build();
                BleManager.getInstance().initScanRule(scanRuleConfig);
                BleManager.getInstance().scan(new BleScanCallback() {
                    @Override
                    public void onScanFinished(List<BleDevice> scanResultList) {
                        if (null != scanResultList && !scanResultList.isEmpty()) {
                            for (int i = 0; i < scanResultList.size(); i++) {
                                BleDevice bleDevice = scanResultList.get(i);
                                String name = bleDevice.getName();
                                if (!TextUtils.isEmpty(name)) {
                                    deviceList.add(bleDevice);
                                }
                            }
                            LogUtils.d(deviceList.size());
                            if (!deviceList.isEmpty()) {
                                bleScanAdapter.notifyDataSetChanged();
                                binding.loadingLAV.cancelAnimation();
                                binding.loadingLAV.setVisibility(View.GONE);
                            } else {
                                PopTip.show("未找到蓝牙称!");
                            }
                        }
                    }

                    @Override
                    public void onScanStarted(boolean success) {
                    }

                    @Override
                    public void onScanning(BleDevice bleDevice) {
                    }
                });
            }
        });
        binding.cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        binding.loadingLAV.cancelAnimation();
        if (BleManager.getInstance().getScanSate() == BleScanState.STATE_SCANNING) {
            BleManager.getInstance().cancelScan();
        }
    }
}
