package com.rdiot.yx485.device.view;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.rdiot.yx485.util.DialogUtils.showAlertDialog;
import static com.rdiot.yx485.util.IntentUtils.intentToAddDevice;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.rdiot.yx485.BaseActivity;
import com.rdiot.yx485.adapter.DeviceListAdapter;
import com.rdiot.yx485.bean.EditDeviceReplyBean;
import com.rdiot.yx485.databinding.ActivityDeviceEditBinding;
import com.rdiot.yx485.device.model.BindViewModel;

import java.util.List;

public class DeviceManageActivity extends BaseActivity {
    private final BindViewModel mViewModel = new BindViewModel();
    private ActivityDeviceEditBinding mBinding;

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

        initView();
        initDate();
    }

    private void initView() {
        mBinding.layoutTitle.btnTitleLeft.setOnClickListener(v -> finish());
        mBinding.layoutTitle.tvTitle.setText("设备管理");
        mBinding.layoutTitle.btnTitleRight.setText("添加设备");
        mBinding.layoutTitle.btnTitleRight.setOnClickListener(v -> intentToAddDevice(this));
    }

    /**
     * 设备列表
     */
    private void initDate() {
        mViewModel.getErrorMessage().observe(this, this::showMessage);
        mViewModel.getDeviceList().observe(this, this::setupRecyclerView);
        mViewModel.loadDeviceList(null);
    }

    @SuppressLint("NotifyDataSetChanged")
    private void setupRecyclerView(List<EditDeviceReplyBean.DataBean.DeviceBean> data) {
        if (data == null || data.isEmpty()) {
            mBinding.tvDataEmpty.setVisibility(VISIBLE);
            return;
        }

        mBinding.tvDataEmpty.setVisibility(GONE);
        mBinding.deviceList.setLayoutManager(new LinearLayoutManager(this));
        DeviceListAdapter myAdapter = new DeviceListAdapter(this, data);
        myAdapter.setDeleteListener(deviceId -> showAlertDialog(this,
                "删除设备",
                "确定要删除该设备吗？",
                (dialog, which) -> mViewModel.deleteDevice(deviceId),
                (dialog, which) -> myAdapter.notifyDataSetChanged()));
        mBinding.deviceList.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
    }
}