package com.example.blu.toys.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.LogUtils;
import com.clj.fastble.data.BleDevice;
import com.example.blu.toys.R;
import com.example.blu.toys.adapter.BleDeviceAdapter;
import com.example.blu.toys.ble.BlePlay;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

import butterknife.BindView;
import butterknife.OnClick;

public class SelectDeviceActivity extends BaseActivity {

	@BindView(R.id.recyclerView)
	RecyclerView mRecyclerView;

	BleDeviceAdapter bleDeviceAdapter;
	private List<BleDevice> bleDevices;

	@Override
	public int getLayout() {
		return R.layout.activity_seleclt_device;
	}

	@Override
	public void init(Bundle savedInstanceState) {
		EventBus.getDefault().register(this);
		if (bleDevices == null) {
			bleDevices = new ArrayList<>();
		}
		mRecyclerView.setLayoutManager(getLinearLayout());
		bleDeviceAdapter = new BleDeviceAdapter(R.layout.ble_devices_item, bleDevices);
		mRecyclerView.setAdapter(bleDeviceAdapter);
	}

	@Override
	public void initData() {
		bleDeviceAdapter.setOnItemClickListener((adapter, view, position) -> {
			BleDevice bleDevice = (BleDevice) adapter.getItem(position);
			BlePlay.getInstance().connectedBleDevice(bleDevice);
		});
		showBleDevices();
	}


	public void showBleDevices() {
		List<BleDevice> bles = BlePlay.getInstance().getScanResultList();
		if (CollectionUtils.isEmpty(bles)) {
			return;
		}

		bleDevices.clear();
		for (int i = 0; i < bles.size(); i++) {
			BleDevice bleDevice = bles.get(i);
			String deviceName = bleDevice.getName();
			if (!TextUtils.isEmpty(deviceName) && deviceName.contains("Traffic")) {
				bleDevices.add(bleDevice);
			}
		}
		if (bleDeviceAdapter != null) {
			bleDeviceAdapter.notifyDataSetChanged();
		}
	}


	@Subscribe(threadMode = ThreadMode.MAIN)
	public void connDevices(BleDevice ble) {
		LogUtils.e("连接 成功");
		goActivity(SetTimeActivity.class);
	}


	@OnClick(R.id.back_but)
	public void onViewClicked() {
		Intent intent = new Intent(SelectDeviceActivity.this, AddDeviceActivity.class);

		startActivity(intent);
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(SelectDeviceActivity.this, AddDeviceActivity.class);

		startActivity(intent);
	}
}