package com.sheep.gamegroup.view.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import com.sheep.gamegroup.model.entity.Article;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewHolder;

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

/**
 * Created by ljy on 2018/3/20.
 */

public abstract class AdbCommonRecycler<T> extends RecyclerView.Adapter<ViewHolder> {
    Context context;
    List<T> listData = new ArrayList<>();

    public AdbCommonRecycler(Context context) {
        this.context = context;
    }

    public AdbCommonRecycler(Context context, List<T> list) {
        this.context = context;
        listData = list;
    }

    public Context getContext() {
        return context;
    }

    public void addAll(List<T> listData) {
        this.listData.addAll(listData);
    }

    public void add(T t) {
        this.listData.add(t);
    }

    public void add(T t, int position) {
        this.listData.set(position, t);
    }

    public void clear() {
        this.listData.clear();
    }

    public abstract int getViewIdByType(int type);

    public abstract void convert(ViewHolder holder, T t);

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            holder.updatePosition(position);
            convert(holder, ListUtil.getItem(listData, position));
        }
    }

    @Override
    public @NonNull ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return ViewHolder.get(context, null, viewGroup, getViewIdByType(i), -1);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        viewHolder.updatePosition(position);
        convert(viewHolder, ListUtil.getItem(listData, position));
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    public interface Converter{
        void convert(ViewHolder holder, Article item);
    }
}
