package com.epam.cdp.jee.todo.persistence.repository.jpa;

import lombok.extern.slf4j.Slf4j;

import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import com.epam.cdp.jee.todo.persistence.Jpa;
import com.epam.cdp.jee.todo.persistence.entity.Task;
import com.epam.cdp.jee.todo.persistence.repository.TaskRepository;

@Stateless
@Slf4j
@Jpa
public class TaskJpaRepository implements TaskRepository {

    @Inject
    private EntityManager entityManager;

    @Override
    public void add(final Task task) {
        entityManager.merge(task);
    }

    @Override
    public void remove(final Task task) {
        entityManager.remove(task);
    }

    @Override
    public List<Task> list() {
        List<Task> tasks;
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Task> query = criteriaBuilder.createQuery(Task.class);
        query.distinct(true).from(Task.class);
        tasks = entityManager.createQuery(query).getResultList();
        return tasks;
    }

    @Override
    public List<Task> list(final String tagName) {
        List<Task> tasks;
        Query query = entityManager.createQuery("SELECT t FROM Task t INNER JOIN t.tags tag WHERE tag.name = :tagName", Task.class);
        query.setParameter("tagName", tagName);
        tasks = query.getResultList();
        return tasks;
    }

    @Override
    public Task findById(final Long taskId) {
        throw new UnsupportedOperationException();
    }
}

@@ -337,16 +337,56 @@
 iaQuery;
+%0Aimport javax.persistence.criteria.Root;
 %0A%0Aimport
@@ -928,34 +928,8 @@
 ) %7B%0A
-        List%3CTask%3E tasks;%0A
     
@@ -1091,62 +1091,173 @@
     
-query.distinct(true).from(Task.class);%0A        tasks =
+Root%3CTask%3E taskRoot = query.from(Task.class);%0A        query.select(taskRoot);%0A        query.orderBy(criteriaBuilder.asc(taskRoot.get(%22dueDateTime%22)));%0A        return
  ent
@@ -1303,38 +1303,16 @@
 List();%0A
-        return tasks;%0A
     %7D%0A%0A 
@@ -1379,34 +1379,8 @@
 ) %7B%0A
-        List%3CTask%3E tasks;%0A
     
@@ -1492,16 +1492,43 @@
 :tagName
+ ORDER BY t.dueDateTime ASC
 %22, Task.
@@ -1595,15 +1595,14 @@
     
-tasks =
+return
  que
@@ -1625,30 +1625,8 @@
 ();%0A
-        return tasks;%0A
     

Add ordering by task due date