
import java.util.List;
import javax.ejb.*;
import org.jboss.seam.annotations.*;
import org.jboss.seam.annotations.datamodel.*;
import org.jboss.seam.ejb.*;
import org.hibernate.validator.Valid;

import javax.persistence.*;

import static javax.persistence.PersistenceContextType.EXTENDED;

@Stateful
@Name("todoDao")
public class TodoDao implements TodoDaoInt {

  @In (required=false) @Out (required=false)
  private Todo todo;

  @PersistenceContext (type=EXTENDED)
  private EntityManager em;

  // Injected from pages.xml
  Long id;
 
  public String persist () {
    em.persist (todo);
    return "persisted";
  }

  @DataModel
  private List <Todo> todos;

  @Factory("todos")
  public void findTodos () {
    todos = em.createQuery("select t from Todo t")
                                  .getResultList();
  }

  public void setId (Long id) {
    this.id = id;
    
    if (id != null) {
      todo = (Todo) em.find(Todo.class, id);
    } else {
      todo = new Todo ();
    }
  }
  
  public Long getId () {
    return id;
  }

  public String delete () {
    em.remove( todo );
    return "removed";
  }

  public String update () {
    return "updated";
  }

  @Remove @Destroy
  public void destroy() {}

}

