package hf.lskj.com.carstockcount.adapter;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;

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

import hf.lskj.com.carstockcount.db.CarInfo;

/**
 * Created by yaoju on 2017/8/3.
 */

public class VinAdapter extends ArrayAdapter<String> {

    private MyFilter mFilter;
    private List<String> mVinList;
    private List<String> backData;

    public VinAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<String> vinList) {
        super(context, resource, vinList);
        mVinList = vinList;
        backData = mVinList;
    }

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

    @Nullable
    @Override
    public String getItem(int position) {
        return mVinList.get(position);
    }

    @Override
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new MyFilter();
        }
        return mFilter;
    }

    // 自定义Filter类
    private class MyFilter extends Filter {
        @Override
        // 该方法在子线程中执行
        // 自定义过滤规则
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<String> newValues = new ArrayList<>();
            // 如果搜索框内容为空，就恢复原始数据
            if (TextUtils.isEmpty(constraint)) {
                newValues = backData;
            } else {
                String filterString = constraint.toString().trim()
                        .toLowerCase();
                if (filterString.equals("")) {
                    newValues = backData;
                } else {
                    // 过滤出新数据
                    for (String str : backData) {
                        if (str.contains(constraint)) {
                            newValues.add(str);
                        }
                    }
                }
            }
            results.values = newValues;
            results.count = newValues.size();
            return results;
        }

        //在publishResults方法中告诉适配器更新界面
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            mVinList = (List<String>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();//通知数据发生了改变
            } else {
                notifyDataSetInvalidated();//通知数据失效
            }
        }
    }
}
