package com.yidian.common.base;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;

public class BaseHeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final int type_header = -1;
    private RecyclerView.Adapter targetAdapter;
    private View headerView;
    private int headerViewRes;
 
    public BaseHeaderAdapter(RecyclerView.Adapter targetAdapter,View headerView) {
        this.targetAdapter = targetAdapter;
        this.headerView = headerView;
    }

    public BaseHeaderAdapter(RecyclerView.Adapter targetAdapter,int headerViewRes) {
        this.targetAdapter = targetAdapter;
        this.headerViewRes = headerViewRes;
    }
 
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == type_header) {
            if(headerView!=null){
                return new ZeroViewHolder(headerView);
            }else {
                View view = LayoutInflater.from(parent.getContext()).inflate(headerViewRes, parent, false);
                return new ZeroViewHolder(view);
            }
        }
        return targetAdapter.onCreateViewHolder(parent,viewType);
    }
 
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        switch (holder.getItemViewType()) {
            case type_header:
                break;
            default:
                targetAdapter.onBindViewHolder(holder,position-1);
                break;
        }
    }
 
    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return type_header;
        } else {
            return targetAdapter.getItemViewType(position-1);
        }
    }
 
    @Override
    public int getItemCount() {
        return targetAdapter.getItemCount()+1;
    }
 
    static class ZeroViewHolder extends RecyclerView.ViewHolder {
 
        public ZeroViewHolder(View itemView) {
            super(itemView);
        }
    }
}