package com.wishurgift.persistence.repository.bean;

import com.wishurgift.persistence.entity.User;
import com.wishurgift.persistence.repository.PersistableRepository;
import com.wishurgift.persistence.repository.UserRepository;
import com.wishurgift.utils.StringUtils;

import javax.ejb.Stateless;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.Optional;

@Stateless
public class UserRepositoryBean extends PersistableRepository<User> implements UserRepository {

    @Override
    public User getByEmail(String email) {
        TypedQuery<User> query = entityManager.createNamedQuery(User.FIND_BY_EMAIL, User.class);
        query.setParameter("email", email);
        List<User> result = query.getResultList();
        if (result.size() > 0) {
            return result.get(0);
        }
        return null;
    }

    @Override
    public Optional<User> findByEmail(String email) {
        User result = getByEmail(email);
        if (result == null) {
            return Optional.empty();
        }
        return Optional.of(result);
    }

    @Override
    public User getByTag(String tag) {
        TypedQuery<User> query = entityManager.createNamedQuery(User.FIND_BY_TAG, User.class);
        query.setParameter("tag", tag);
        List<User> result = query.getResultList();
        if (result.size() > 0) {
            return result.get(0);
        }
        return null;
    }

    @Override
    public Optional<User> findByTag(String tag) {
        User result = getByTag(tag);
        if (result == null) {
            return Optional.empty();
        }
        return Optional.of(result);
    }

    @Override
    public List<User> search(String request, int limit) {
        TypedQuery<User> query = entityManager.createNamedQuery(User.SEARCH, User.class);
        query.setParameter("search", "%" + StringUtils.lower(request) + "%");
        if (limit > 0) {
            query.setMaxResults(limit);
        }
        return query.getResultList();
    }

    @Override
    protected Class<User> getEntityClass() {
        return User.class;
    }

}
