package com.qy.test.weiget.recyclerview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qy.test.base.R;
import com.qy.test.reflect.FieldDisplayItem;
import com.qy.test.reflect.ReflectUtils;

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

public class CustomBaseListView extends ViewGroup {

    private RecyclerView  mRecyclerView;
    private List<FieldDisplayItem> mData;
    private CustomListAdapter mAdapter;
    private OnItemClickListener mItemClickListener;

    public CustomBaseListView(Context context) {
        super(context);

        init(context);
    }

    public CustomBaseListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        mData = new ArrayList<>();
        View view = LayoutInflater.from(context).inflate(R.layout.base_layout_custom_list, this, false);

        mRecyclerView = view.findViewById(R.id.rv_RecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        mAdapter = new CustomListAdapter(context, mData, position -> {
            if (mItemClickListener != null){
                mItemClickListener.onItemClick(position);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        addView(view);
    }

    public void setData(Object bean) {
        mData.clear();
        List<FieldDisplayItem> list = ReflectUtils.extractAnnotatedFields(bean);
        mData.addAll(list);
        mAdapter.notifyDataSetChanged();
    }

    public void setItemClickListener(OnItemClickListener listener){
        this.mItemClickListener = listener;
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (getChildCount() > 0) {
            View child = getChildAt(0);
            child.layout(0, 0, getMeasuredWidth(), getMeasuredHeight());
        }
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getChildCount() > 0) {
            View child = getChildAt(0);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }
    }


    public interface OnItemClickListener {
        void onItemClick(int position);

    }
}
