package com.rdiot.yx485.device.view;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rdiot.yx485.R;
import com.rdiot.yx485.adapter.DeviceTypeListAdapter;
import com.rdiot.yx485.base.BaseFragment;
import com.rdiot.yx485.bean.DeviceTreeBean;

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

public class DeviceTypeFragment extends BaseFragment {
    private static final String ARG_DEVICE_LIST = "device_list";
    private List<DeviceTreeBean.DataBean.ChildrenBean> mDeviceList;
    private RecyclerView mRecyclerView;
    private DeviceTypeListAdapter mAdapter;

    public static DeviceTypeFragment newInstance(List<DeviceTreeBean.DataBean.ChildrenBean> deviceList) {
        DeviceTypeFragment fragment = new DeviceTypeFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_DEVICE_LIST, new ArrayList<>(deviceList));
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mDeviceList = (List<DeviceTreeBean.DataBean.ChildrenBean>) getArguments().getSerializable(ARG_DEVICE_LIST);
        }
    }

    @Override
    public void onViewCreated(@NonNull android.view.View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        setupRecyclerView();
    }

    private void setupRecyclerView() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 3));
        mAdapter = new DeviceTypeListAdapter(mDeviceList, this::gotoDeviceBind);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void gotoDeviceBind(DeviceTreeBean.DataBean.ChildrenBean item) {
        Bundle bundle = new Bundle();
        bundle.putBoolean("isMaster", item.is_master);
        bundle.putBoolean("bluetooth", item.bluetooth);
        bundle.putBoolean("need_device_code", item.need_device_code);
        bundle.putString("device_type_id", item.record_id);
        bundle.putString("blue_code", item.blue_code);
        bundle.putString("device_name", item.name);
        ResetActivity.newIntent(requireActivity(), bundle, item.steps);
    }

    @Override
    public android.view.View onCreateView(@NonNull android.view.LayoutInflater inflater,
                                          @Nullable android.view.ViewGroup container,
                                          @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_device_type, container, false);
    }
}