package foam.android.view;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.ViewGroup;

import foam.core.DAO;
import foam.core.DAOException;
import foam.core.DAOInternalException;
import foam.core.FindSink;
import foam.core.HasX;
import foam.core.MLang;
import foam.core.X;

/**
 * {@link RecyclerView.Adapter} for use with {@link RecyclerView}s of a {@link DAO}.
 */
public class DAOAdapter extends RecyclerView.Adapter<DAOAdapter.DAOViewHolder> implements HasX {
  private DetailViewFactory viewFactory;
  private DAO dao;
  private X x;
  public X X() {
    return x;
  }
  public void X(X x) {
    this.x = x;
  }

  public DAOAdapter(X x, DAO dao, DetailViewFactory viewFactory) {
    X(x.put("model", dao.getModel()));
    this.dao = dao;
    this.viewFactory = viewFactory;
  }

  @Override
  public int getItemCount() {
    try {
      MLang.CountSink sink = MLang.COUNT();
      dao.select(X(), sink);
      return (int) sink.getCount();
    } catch(DAOInternalException e) {
      Log.e("DAOAdapter", "DAOInternalException while trying to fetch COUNT");
    } catch(DAOException e) {
      Log.e("DAOAdapter", "DAOException while trying to fetch COUNT");
    }
    return 0;
  }

  @Override
  public DAOViewHolder onCreateViewHolder(ViewGroup parent, int position) {
    ViewBridge b = viewFactory.create(parent);
    b.X(X());
    return new DAOViewHolder(b);
  }

  @Override
  public void onBindViewHolder(DAOViewHolder holder, int position) {
    FindSink sink = new FindSink();
    try {
      dao.limit(1).skip(position).select(X(), sink);
    } catch(DAOException e) {
      Log.e("DAOAdapter", "DAOException while trying to bind a view.");
      return;
    } catch(DAOInternalException e) {
      Log.e("DAOAdapter", "DAOInternalException while trying to bind a view.");
      return;
    }
    holder.viewBridge.getValue().set(sink.getValue());
  }

  class DAOViewHolder extends RecyclerView.ViewHolder {
    public final ViewBridge viewBridge;
    public DAOViewHolder(ViewBridge itemView) {
      super(itemView.getView());
      viewBridge = itemView;
    }
  }
}

@@ -93,16 +93,42 @@
 il.Log;%0A
+import android.view.View;%0A
 import a
@@ -317,16 +317,40 @@
 .MLang;%0A
+import foam.core.Value;%0A
 import f
@@ -2012,16 +2012,48 @@
 wHolder 
+implements View.OnClickListener 
 %7B%0A    pu
@@ -2196,16 +2196,387 @@
 emView;%0A
+      // If selection is defined, then we should bind to click events.%0A      if (viewBridge.X().get(%22selection%22) != null)%0A        itemView.getView().setOnClickListener(this);%0A    %7D%0A%0A    @Override%0A    public void onClick(View view) %7B%0A      Value selection = (Value) viewBridge.X().get(%22selection%22);%0A      if (selection != null) selection.set(viewBridge.getValue().get());%0A
     %7D%0A  

Add onClick to DAOListView when selection is set on the context