package com.zhaohaoting.framework.abs.adapter;

import android.content.Context;
import android.widget.BaseAdapter;

import com.zhaohaoting.framework.mvchelper.mvc.IDataAdapter;

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


/**
 * author：Created by ZHT on 2017/11/1 16:13
 * email：526309416@qq.com
 * desc：列表类界面 基类适配器
 */
@SuppressWarnings("unchecked")
public abstract class BaseListAdapter<DATA, RESULT_DATA> extends BaseAdapter implements IDataAdapter<RESULT_DATA> {

    //    private Class<DATA> tCls;
    private Class<RESULT_DATA> resultCls;
    protected List<DATA> mDataList;
    protected Context mContext;

    public BaseListAdapter(List<DATA> dataList, Context context) {
//        tCls = (Class<DATA>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Type type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        if (type instanceof ParameterizedType) {
            resultCls = (Class<RESULT_DATA>) ((ParameterizedType) type).getRawType();
        }else {
            resultCls = (Class<RESULT_DATA>) type;
        }
        mDataList = dataList;
        this.mContext = context;
    }

    @Override
    public int getCount() {
        return mDataList.size();
    }

    @Override
    public Object getItem(int position) {
        return mDataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public void notifyDataChanged(RESULT_DATA dataList, boolean isRefresh) {
        if (isRefresh) {
            mDataList.clear();
        }
        if (resultCls.isAssignableFrom(List.class)) {
            mDataList.addAll((List<DATA>) dataList);
            notifyDataSetChanged();
            return;
        } else {
            throw new IllegalArgumentException("If BASE_DATA is not a List subclass, you need to override this method.");
        }
    }

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

    @Override
    public boolean isEmpty() {
        return super.isEmpty();
    }
}