package org.codiki.core.repositories;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.codiki.core.entities.persistence.Post;
import org.codiki.core.utils.StringUtils;

public class PostSearchRepositoryImpl implements PostSearchRepository {
	@PersistenceContext
	private EntityManager em;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Post> search(final String[] pCriterias) {
		List<Post> result = new LinkedList<>();
		
		final String queryStr = buildSearchQuery(pCriterias);
		try {
			final Query query = em.createNativeQuery(queryStr, Post.class);
			for(int i = 1 ; i <= pCriterias.length ; i++) {
				query.setParameter(StringUtils.concat("c", i), StringUtils.concat('%', pCriterias[i - 1].toLowerCase(), '%'));
			}
			result = query.getResultList();
		} catch(final PersistenceException pEx) {
			// TODO
		}
		
		return result;
	}
	
	protected String buildSearchQuery(final String[] pCriterias) {
		final StringBuilder result = new StringBuilder("SELECT * FROM post p INNER JOIN category c ON c.id = category_id INNER JOIN \"user\" u ON u.id = p.creator_id ");
		
		for(int i = 1 ; i <= pCriterias.length ; i++) {
			result.append(StringUtils.concat((i == 1) ? "WHERE" : "OR", " UNACCENT(p.title) ILIKE UNACCENT(:c", i, ")",
					" OR UNACCENT(p.description) ILIKE UNACCENT(:c", i, ")",
					" OR UNACCENT(p.text) ILIKE UNACCENT(:c", i, ")",
					" OR UNACCENT(c.name) ILIKE UNACCENT(:c", i, ")",
					" OR UNACCENT(u.name) ILIKE UNACCENT(:c", i, ")",
					" OR UNACCENT(u.email) ILIKE UNACCENT(:c", i, ") "));
		}
		
		return result.toString();
	}
}
