package com.mjsheng.myappstore.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.bean.AppData;
import com.mjsheng.myappstore.bean.SearchBean;

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

public class SearchHistoryAdapter extends BaseAdapter {
    private Context context;
    public List<SearchBean> histories = new ArrayList<>();

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



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

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

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_saerch_history, null);
            holder = new ViewHolder();
            holder.cancelIv = (ImageView) convertView.findViewById(R.id.iv_history_cancel);
            holder.historyTv = (TextView) convertView.findViewById(R.id.tv_history);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (histories.get(position) != null) {
            holder.historyTv.setText(histories.get(position).getCategory());
            holder.cancelIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppData.deleteSearchData(context, histories.get(position).getCategory());
                    for (SearchBean bean : histories) {
                        if (bean.getCategory().equals(histories.get(position).getCategory())) {
                            histories.remove(bean);
                            notifyDataSetChanged();
                            return;
                        }
                    }
                }
            });
        }

        return convertView;
    }

    class ViewHolder {
        public TextView historyTv;
        public ImageView cancelIv;
    }
}
