package com.zhaohaoting.framework.abs.adapter;

import android.support.v7.widget.RecyclerView;

import com.zhaohaoting.framework.recyclerview.adapter.BaseQuickAdapter;
import com.zhaohaoting.framework.recyclerview.holder.BaseQuickViewHolder;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * author：Created by zhaohaoting on 2018/7/25 10:31
 * email：526309416@qq.com
 * desc：RESULT_DATA 如果不是列表 要重写notifyDataChanged和个体getData两个方法
 */
@SuppressWarnings("unchecked")
public abstract class SingleItemQuickAdapter<DATA, RESULT_DATA, HOLDER extends BaseQuickViewHolder> extends BaseQuickAdapter<DATA, RESULT_DATA, HOLDER> {

    private Class<RESULT_DATA> resultCls;

    public SingleItemQuickAdapter(RecyclerView recyclerView, int layoutResId, List<DATA> data) {
        super(recyclerView, layoutResId, data);
        resultCls = (Class<RESULT_DATA>) ((ParameterizedType) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]).getRawType();
    }

    public SingleItemQuickAdapter(RecyclerView recyclerView, List<DATA> data) {
        this(recyclerView, 0, data);
    }

    /**
     * 此处默认数据集（即服务器返回数据data）为list 若是其它数据集需重写此方法
     *
     * @param result_data
     * @param isRefresh
     */
    @Override
    public void notifyDataChanged(RESULT_DATA result_data, boolean isRefresh) {
        if (isRefresh) {
            mData.clear();
        }
        if (resultCls.isAssignableFrom(List.class)) {
            mData.addAll((List<DATA>) result_data);
            notifyDataSetChanged();
        } else {
            throw new IllegalArgumentException("If BASE_DATA is not a List subclass, you need to override this method.");
        }
    }

    /**
     * 同上{@notifyDataChanged}
     *
     * @getData
     */
    @Override
    public RESULT_DATA getData() {
        if (resultCls.isAssignableFrom(List.class)) {
            return (RESULT_DATA) mData;
        } else {
            throw new IllegalArgumentException("If BASE_DATA is not a List subclass, you need to override this method.");
        }
    }

    @Override
    public boolean isEmpty() {
        return getItemCount() == 0;
    }
}
