package cronapi.odata.server;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cronapi.QueryManager;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.jpa.metadata.api.JPAEdmExtension;
import org.apache.olingo.jpa.metadata.core.edm.mapper.impl.IntermediateEntitySet;
import org.apache.olingo.jpa.metadata.core.edm.mapper.impl.IntermediateEntityType;
import org.apache.olingo.jpa.processor.core.api.JPAODataGetHandler;
import org.apache.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor;
import org.apache.olingo.jpa.processor.core.mapping.JPAPersistenceAdapter;
import org.apache.olingo.jpa.processor.core.mapping.ResourceLocalPersistenceAdapter;
import org.apache.olingo.server.api.processor.Processor;
import org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser;
import org.eclipse.persistence.jpa.JpaQuery;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;
import java.util.Map;


public class ODataServletV4 extends HttpServlet {

  private static final long serialVersionUID = 1L;

  private EntityManagerFactory entityManagerFactory;
  private String namespace;

  ODataServletV4(EntityManagerFactory entityManagerFactory, String namespace) {
    this.entityManagerFactory = entityManagerFactory;
    this.namespace = namespace;
  }

  @Override
  protected void service(final HttpServletRequest req, final HttpServletResponse resp)
      throws ServletException {

    try {
      JPAODataGetHandler handler = createHandler();
      handler.process(req, resp);
    } catch (final ODataException e) {
      throw new ServletException(e);
    }

  }

  private JPAODataGetHandler createHandler() throws ODataException {

    final JPAPersistenceAdapter mappingAdapter = new ResourceLocalPersistenceAdapter(namespace,
        entityManagerFactory,
        new JPADefaultDatabaseProcessor());
    final JPAODataGetHandler handler = new JPAODataGetHandler(mappingAdapter) {
      @Override
      protected Collection<Processor> collectProcessors(final HttpServletRequest request,
                                                        final HttpServletResponse response, final EntityManager em) {
        final Collection<Processor> processors = super.collectProcessors(request, response, em);
        processors.add(new ODataErrorProcessor());
        return processors;
      }
    };

    handler.setJPAEdmExtension(new JPAEdmExtension() {
      @Override
      public void extendJPAEntitySet(Map<String, IntermediateEntitySet> set) {
        JsonObject queries = QueryManager.getJSON();

        for (Map.Entry<String, JsonElement> entry : queries.entrySet()) {
          JsonObject customObj = entry.getValue().getAsJsonObject();
          if (!QueryManager.isNull(customObj.get("entityFullName"))) {
            String clazz = customObj.get("entityFullName").getAsString();
            if (clazz.startsWith(namespace)) {
              try {
                createDataSource(set, entry.getKey(), clazz);
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          }
        }
      }

      @Override
      public TypedQuery createQuery(EntityManager em, CriteriaQuery<Tuple> criteria) {
        JPQLParser parser = JPQLParser.buildParserFor("select c from Teste c where c.Id = 'asdsad' ");
        parser.parse();


        //parser.getParseTree().getWhereNode()

        //criteria.
      //  TypedQuery<Tuple> query = em.createQuery(

        //    "select c.id as id, c.id2 as id2 from Teste c", Tuple.class);

       // List<Tuple> results = query.getResultList();

        TypedQuery<Tuple> xy = em.createQuery(criteria);

        String jpql = xy.unwrap(JpaQuery.class).getDatabaseQuery().getJPQLString();

        return em.createQuery(criteria);

        //return super.createQuery(criteria);
      }
    });

    return handler;
  }

  private void createDataSource(Map<String, IntermediateEntitySet> set, String id, String entityNamespace) throws Exception {

    IntermediateEntitySet foundES = null;

    for (IntermediateEntitySet entity : set.values()) {
      if (entity.getEntityType().getTypeClass().getName().equals(entityNamespace)) {
        foundES = entity;
        break;
      }
    }

    if (foundES != null) {
      IntermediateEntitySet newSet = new IntermediateEntitySet(foundES.getNameBuilder(), (IntermediateEntityType) foundES.getEntityType());
      newSet.setExternalName(id);
      set.put(foundES.getInternalName() + "_" + id, newSet);
    }
  }


}

@@ -28,108 +28,8 @@
 r;%0A%0A
-import com.google.gson.JsonElement;%0Aimport com.google.gson.JsonObject;%0Aimport cronapi.QueryManager;%0A
 impo
@@ -675,324 +675,92 @@
 or;%0A
-import org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser;%0Aimport org.eclipse.persistence.jpa.JpaQuery;%0A%0Aimport javax.persistence.EntityManager;%0Aimport javax.persistence.EntityManagerFactory;%0Aimport javax.persistence.Tuple;%0Aimport javax.persistence.TypedQuery;%0Aimport javax.persistence.criteria.CriteriaQue
+%0Aimport javax.persistence.EntityManager;%0Aimport javax.persistence.EntityManagerFacto
 ry;%0A
@@ -963,31 +963,8 @@
 on;%0A
-import java.util.List;%0A
 impo
@@ -2552,477 +2552,79 @@
     
-JsonObject queries = QueryManager.getJSON();%0A%0A        for (Map.Entry%3CString, JsonElement%3E entry : queries.entrySet()) %7B%0A          JsonObject customObj = entry.getValue().getAsJsonObject();%0A          if (!QueryManager.isNull(customObj.get(%22entityFullName%22))) %7B%0A            String clazz = customObj.get(%22entityFullName%22).getAsString();%0A            if (clazz.startsWith(namespace)) %7B%0A              try %7B%0A                createDataSource(set, entry.getKey(), clazz);%0A      
+try %7B%0A          createDataSource(set, %22Thiago%22, %22app.entity.Company%22);%0A
     
@@ -2661,22 +2661,16 @@
         
-      
 e.printS
@@ -2694,777 +2694,9 @@
     
-      %7D%0A            %7D%0A          %7D%0A        %7D%0A      %7D%0A%0A      @Override%0A      public TypedQuery createQuery(EntityManager em, CriteriaQuery%3CTuple%3E criteria) %7B%0A        JPQLParser parser = JPQLParser.buildParserFor(%22select c from Teste c where c.Id = 'asdsad' %22);%0A        parser.parse();%0A%0A%0A        //parser.getParseTree().getWhereNode()%0A%0A        //criteria.%0A      //  TypedQuery%3CTuple%3E query = em.createQuery(%0A%0A        //    %22select c.id as id, c.id2 as id2 from Teste c%22, Tuple.class);%0A%0A       // List%3CTuple%3E results = query.getResultList();%0A%0A        TypedQuery%3CTuple%3E xy = em.createQuery(criteria);%0A%0A        String jpql = xy.unwrap(JpaQuery.class).getDatabaseQuery().getJPQLString();%0A%0A        return em.createQuery(criteria);%0A%0A        //return super.createQuery(criteria);
+%7D
 %0A   

Revert "Evoluçao"