package com.mayi.fastdevelop.view.lazyLoading;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.mayi.fastdevelop.R;

import java.util.List;

import static androidx.recyclerview.widget.RecyclerView.*;

public abstract class ListLazyLoadingAdapter<T extends ViewHolder> extends ListLazyLoadingView.Adapter {

    public static final int LOADMORE_VIEWTYPE = -1;

    private boolean isShowLoadMore = true;

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == LOADMORE_VIEWTYPE) {
            return getLoadMoreVH(parent);
        } else {
            return getCreateViewHolder( parent,viewType);
        }
    }

    //获取加载更多VH，子类可重现
    public ViewHolder getLoadMoreVH(@NonNull ViewGroup parent) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).
                inflate(R.layout.item_list_lazy_loading_load_more, parent, false)){
        };
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (position < getList().size()) {
            onBindItemVH((T) holder, position);
        }
    }

    @Override
    public int getItemCount() {
        if (getList() == null) {
            return 0;
        } else {
            if (isShowLoadMore) {
                return getList().size() + 1;
            } else {
                return getList().size();
            }
        }
    }

    public abstract void onBindItemVH(@NonNull T holder, int position);

    public abstract List getList();

    public abstract T getCreateViewHolder(@NonNull ViewGroup parent,int viewType);


    @Override
    public int getItemViewType(int position) {
        if (isShowLoadMore && position + 1 == getItemCount()) {
            return LOADMORE_VIEWTYPE;
        }
        return super.getItemViewType(position);
    }

    public boolean isShowLoadMore() {
        return isShowLoadMore;
    }

    public void setShowLoadMore(boolean showLoadMore) {
        isShowLoadMore = showLoadMore;
    }

}
