package com.rdiot.yx485.room;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.rdiot.yx485.adapter.RoomAdapter;
import com.rdiot.yx485.base.BaseFragment;
import com.rdiot.yx485.bean.DeviceRoomListBean;
import com.rdiot.yx485.databinding.ActivityRoomManagementBinding;
import com.rdiot.yx485.util.DialogUtils;

import java.util.List;

public class RoomListFragment extends BaseFragment {
    private ActivityRoomManagementBinding mBinding;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = ActivityRoomManagementBinding.inflate(inflater, container, false);
        initView();
        initData();
        return mBinding.getRoot();
    }

    private void initData() {
        RoomViewModel viewModel = new ViewModelProvider(requireActivity()).get(RoomViewModel.class);
        viewModel.getRoomList().observe(getViewLifecycleOwner(), this::setupRecyclerView);
    }

    private void initView() {
        mBinding.addRoomButton.setOnClickListener(v -> DialogUtils.showInputDialog(requireActivity(), "添加房间", null, "请输入房间名称", roomName -> {
            if (getActivity() instanceof RoomManageActivity) {
                ((RoomManageActivity) getActivity()).createRoom(roomName);
            }
        }));
    }

    @SuppressLint("NotifyDataSetChanged")
    private void setupRecyclerView(List<DeviceRoomListBean.RoomBean> data) {
        if (data == null || data.isEmpty()) {
            mBinding.tvDataEmpty.setText("暂无数据");
        } else {
            mBinding.tvDataEmpty.setText("");
        }

        RoomAdapter adapter = new RoomAdapter(data);
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        mBinding.recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
}
