package at.fhj.swd14.pse.news;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Stateless
public class NewsServiceImpl implements NewsService {

    private static final Logger LOGGER = LogManager.getLogger(NewsServiceImpl.class);

    @EJB
    private NewsRepository newsRepository;

    @Override
    public long save(NewsDto news) {
        try {
            final News converted = NewsConverter.convert(Objects.requireNonNull(news));
            newsRepository.save(converted);
            return converted.getId();
        } catch (Exception e) {
            LOGGER.warn(e);
            throw new NewsServiceException("Could not save news");
        }
    }

    @Override
    public long update(NewsDto news) {
        try {
            final News converted = NewsConverter.convert(Objects.requireNonNull(news));
            newsRepository.update(converted);
            return converted.getId();
        } catch (Exception e) {
            LOGGER.warn(e);
            throw new NewsServiceException("Could not update news");
        }
    }

    @Override
    public NewsDto find(long id) {
        try {
            return NewsConverter.convert(newsRepository.find(id));
        } catch (Exception e) {
            LOGGER.info(e);
            throw new NewsServiceException("Could not find news");
        }
    }

    @Override
    public Collection<NewsDto> findAll() {
        try {
            return NewsConverter.convertToDtoList(newsRepository.findAll());
        } catch (Exception e) {
            LOGGER.info(e);
            throw new NewsServiceException("Could not find any news");
        }
    }

    @Override
    public Collection<NewsDto> findAllOnline() {
        try {
            final Map<String, Object> parameters = new HashMap<>();
            parameters.put("onlineDate", ZonedDateTime.now().toInstant());
            return NewsConverter.convertToDtoList(newsRepository.executeNamedQuery(News.FIND_ALL_ONLINE_QUERY, parameters));
        } catch (Exception e) {
            LOGGER.info(e);
            throw new NewsServiceException("Could not find online news");
        }
    }
}

@@ -785,36 +785,52 @@
     LOGGER.warn(
+e.getMessage(), 
 e);%0A
-
             thro
@@ -1192,16 +1192,32 @@
 ER.warn(
+e.getMessage(), 
 e);%0A    
@@ -1476,32 +1476,48 @@
     LOGGER.info(
+e.getMessage(), 
 e);%0A            
@@ -1784,32 +1784,48 @@
     LOGGER.info(
+e.getMessage(), 
 e);%0A            
@@ -2269,32 +2269,32 @@
 (Exception e) %7B%0A
-
             LOGG
@@ -2301,16 +2301,32 @@
 ER.info(
+e.getMessage(), 
 e);%0A    

add missing stacktrace to exception logging