package com.test.testapplication;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

public class NameRecyclerAdapter extends RecyclerView.Adapter<NameRecyclerAdapter.ItemHolder> {

    private List<FavoriteBean> favoriteBeans;

    ItemHolder.IClickHandler clickHandler;

    public NameRecyclerAdapter(List<FavoriteBean> favoriteBeans, ItemHolder.IClickHandler clickHandler) {
        this.favoriteBeans = favoriteBeans;
        this.clickHandler = clickHandler;
    }

    @Override
    public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.name_item, parent, false);

        // create ViewHolder
        return new ItemHolder(itemLayoutView, clickHandler);
    }

    @Override
    public void onBindViewHolder(ItemHolder holder, int position) {
        FavoriteBean favoriteBean = favoriteBeans.get(position);

        holder.favItemTitle.setText( favoriteBean.getTitle() );
        holder.favItemCate.setText( favoriteBean.getCategory() );
        holder.favItemUserCount.setText( favoriteBean.getUsers() );
        holder.favItemDesc.setText( favoriteBean.getDescription() );
        holder.favItemSerial.setText( favoriteBean.getSerialNumberString() );
    }

    @Override
    public int getItemCount() {
        return favoriteBeans.size();
    }

    @Override
    public long getItemId(int position) {
        if( hasStableIds() ){
            return position;
        }
        return RecyclerView.NO_ID;
    }

    public static class ItemHolder extends RecyclerView.ViewHolder {

        LabelView favItemTitle;
        LabelView favItemCate;
        LabelView favItemUserCount;
        LabelView favItemDesc;
        LabelView favItemSerial;

        IClickHandler clickHandler;

        public ItemHolder(View view, IClickHandler clickHandler) {
            super(view);

            favItemTitle = (LabelView) view.findViewById(R.id.favItemTitle);
            favItemCate = (LabelView) view.findViewById(R.id.favItemCate);
            favItemUserCount = (LabelView) view.findViewById(R.id.favItemUserCount);
            favItemDesc = (LabelView) view.findViewById(R.id.favItemDesc);
            favItemSerial = (LabelView) view.findViewById(R.id.favItemSerial);

            this.clickHandler = clickHandler;
            view.setOnClickListener(clickListener);
        }

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getLayoutPosition();
                clickHandler.onClick(v, position);
            }
        };

        public interface IClickHandler {
            void onClick(View caller, int position);
        }
    }
}
