package com.wishurgift.persistence.repository.bean;

import com.wishurgift.persistence.entity.Shared;
import com.wishurgift.persistence.entity.User;
import com.wishurgift.persistence.entity.Wishlist;
import com.wishurgift.persistence.repository.PersistableRepository;
import com.wishurgift.persistence.repository.SharedRepository;

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

@Stateless
public class SharedRepositoryBean extends PersistableRepository<Shared> implements SharedRepository {

    @Override
    public Shared getShared(Wishlist w, User u) {
        TypedQuery<Shared> query = entityManager.createNamedQuery(Shared.FIND, Shared.class);
        query.setParameter("wishlist", w);
        query.setParameter("user", u);
        List<Shared> result = query.getResultList();
        if (result.isEmpty()) {
            return null;
        }
        return result.get(0);
    }

    @Override
    public Optional<Shared> findShared(Wishlist w, User u) {
        Shared shared = getShared(w, u);
        if (shared == null) {
            return Optional.empty();
        }
        return Optional.of(shared);
    }

    @Override
    public List<Shared> getAllFromWishlist(Wishlist w) {
        TypedQuery<Shared> query = entityManager.createNamedQuery(Shared.GET_ALL, Shared.class);
        query.setParameter("wishlist", w);
        return query.getResultList();
    }

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