package com.zatackcoder.viewholderpatternwithbaseadapter;

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

import java.util.List;

class MyBaseAdapter extends BaseAdapter {
    private final Context context;
    private final List<Item> items;

    public MyBaseAdapter(Context context, List<Item> items) {
        this.context = context;
        this.items = items;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if(convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);

            viewHolder = new ViewHolder();
            viewHolder.nameTV = convertView.findViewById(R.id.name);
            viewHolder.priceTV = convertView.findViewById(R.id.price);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        /*
        convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);

        ViewHolder viewHolder = new ViewHolder();
        viewHolder.nameTV = convertView.findViewById(R.id.name);
        viewHolder.priceTV = convertView.findViewById(R.id.price);
        */
        final Item item = items.get(position);

        viewHolder.nameTV.setText(item.getName());
        viewHolder.priceTV.setText(String.valueOf(item.getPrice()));
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "You Just Clicked " + item.getName(), Toast.LENGTH_LONG).show();
            }
        });
        return convertView;
    }

    static class ViewHolder {
        TextView nameTV;
        TextView priceTV;
    }
}
