package com.oguerreiro.resilient.web.rest;

import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.oguerreiro.resilient.domain.Period;
import com.oguerreiro.resilient.domain.enumeration.PeriodStatus;
import com.oguerreiro.resilient.repository.PeriodRepository;
import com.oguerreiro.resilient.service.PeriodService;
import com.oguerreiro.resilient.service.PeriodVersionService;
import com.oguerreiro.resilient.service.dto.PeriodDTO;
import com.oguerreiro.resilient.service.dto.PeriodVersionDTO;

/**
 * REST controller for managing {@link com.oguerreiro.resilient.domain.Period}.
 */
@RestController
@RequestMapping("/api/periods")
public class PeriodResource extends AbstractResilientResource<Period, PeriodDTO, Long> {

  private static final String ENTITY_NAME = "period";

  private final PeriodVersionService periodVersionService;
  private final PeriodService periodService;

  public PeriodResource(PeriodService periodService, PeriodRepository periodRepository,
      PeriodVersionService periodVersionService) {
    super(Period.class, periodRepository, periodService);
    this.periodVersionService = periodVersionService;
    this.periodService = periodService;
  }

  /* AbstractResilientResource methods impl*/
  @Override
  protected String getEntityName() {
    return PeriodResource.ENTITY_NAME;
  }

  /* PeriodResource custom endpoints */
  @GetMapping("/{periodId}/versions")
  public List<PeriodVersionDTO> getAllByPeriod(@PathVariable("periodId") Long periodId) {
    log.debug("REST request to get all getAllByPeriod Id : {}", periodId);
    return periodVersionService.findAllByPeriod(periodId);
  }

  @GetMapping("/{periodId}/lastVersion")
  public PeriodVersionDTO getLatestVersionForPeriod(@PathVariable("periodId") Long periodId) {
    log.debug("REST request to get all getLatestVersionForPeriod Id : {}", periodId);
    return periodVersionService.findLatestVersionForPeriod(periodId);
  }

  @GetMapping("/{periodVersionId}/version")
  public PeriodVersionDTO getVersion(@PathVariable("periodVersionId") Long periodVersionId) {
    log.debug("REST request to get all getVersion Id : {}", periodVersionId);
    return periodVersionService.findOne(periodVersionId).orElseThrow();
  }

  @GetMapping("/byState/{state}")
  public List<PeriodDTO> getAllByState(@PathVariable("state") PeriodStatus state) {
    log.debug("REST request to getAllByStatus : {}", state);
    return periodService.findAllByState(state);
  }
}
