package com.oguerreiro.resilient.service;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oguerreiro.resilient.domain.PeriodVersion;
import com.oguerreiro.resilient.repository.PeriodVersionRepository;
import com.oguerreiro.resilient.service.dto.PeriodVersionDTO;
import com.oguerreiro.resilient.service.mapper.PeriodVersionMapper;

/**
 * Service Implementation for managing {@link com.oguerreiro.resilient.domain.PeriodVersion}.
 */
@Service
@Transactional
public class PeriodVersionService extends AbstractResilientService<PeriodVersionDTO, PeriodVersion, Long> {

  private PeriodVersionRepository periodVersionRepository;
  private PeriodVersionMapper periodVersionMapper;

  public PeriodVersionService(PeriodVersionRepository periodVersionRepository,
      PeriodVersionMapper periodVersionMapper) {
    super(PeriodVersion.class, periodVersionRepository, periodVersionMapper);
    this.periodVersionRepository = periodVersionRepository;
    this.periodVersionMapper = periodVersionMapper;
  }

  public List<PeriodVersionDTO> findAllByPeriod(Long periodId) {
    log.debug("REST request to get all findAllByPeriod Id : {}", periodId);
    //@formatter:off
    return periodVersionRepository.findAllByPeriod(periodId)
            .stream()
            .map(periodVersionMapper::toDto).collect(Collectors.toCollection(LinkedList::new));
    //@formatter:on
  }

  public PeriodVersionDTO findLatestVersionForPeriod(Long periodId) {
    log.debug("REST request to get all findLatestVersionForPeriod Id : {}", periodId);

    List<PeriodVersion> endedVersions = periodVersionRepository.findEndedPeriodVersionsForPeriod(periodId);

    if (endedVersions == null || endedVersions.isEmpty()) {
      return null;
    }

    return periodVersionMapper.toDto(endedVersions.get(0));
  }
}
