package com.oguerreiro.resilient.web.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.oguerreiro.resilient.domain.ContentPage;
import com.oguerreiro.resilient.domain.enumeration.ContentPageType;
import com.oguerreiro.resilient.repository.ContentPageRepository;
import com.oguerreiro.resilient.security.SecurityUtils;

@RestController
@RequestMapping("/api/home")
public class HomeResource {
  private final Logger log = LoggerFactory.getLogger(HomeResource.class);

  private final ContentPageRepository contentPageRepository;

  public HomeResource(ContentPageRepository contentPageRepository) {
    this.contentPageRepository = contentPageRepository;
  }

  /**
   * Get home page HTML. Checks if user is authenticated to give the correct home page
   * 
   * @return
   */
  @GetMapping(value = "/page", produces = MediaType.TEXT_PLAIN_VALUE)
  public String home() {
    log.debug("REST request to get anonymous home page");

    ContentPage home = null;
    if (SecurityUtils.isAuthenticated()) {
      home = this.contentPageRepository.findBySlug(ContentPageType.HOME_AUTHENTICATED);
    } else {
      home = this.contentPageRepository.findBySlug(ContentPageType.HOME_ANONYMOUS);
    }

    return home.getContent();
  }

}
