package com.oguerreiro.resilient.web.rest;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.oguerreiro.resilient.domain.enumeration.OrganizationNature;
import com.oguerreiro.resilient.service.OrganizationService;
import com.oguerreiro.resilient.service.dto.OrganizationDTO;

/**
 * REST controller for environment request
 */
@RestController
@RequestMapping("/api/env")
public class EnvironmentResource {

  private final Logger log = LoggerFactory.getLogger(EnvironmentResource.class);

  private static final String ENTITY_NAME = "environment";

  @Value("${jhipster.clientApp.name}")
  private String applicationName;

  private final OrganizationService organizationService;

  public EnvironmentResource(OrganizationService organizationService) {
    this.organizationService = organizationService;
  }

  /**
   * {@code GET  /organizations} : get the organizations for the current user.
   *
   * @param  eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
   * @return           the {@link ResponseEntity} with status {@code 200 (OK)} and the list of organizations in body.
   */
  @PreAuthorize("@resilientSecurity.canAccess('READ', 'com.oguerreiro.resilient.domain.Organization')")  // Inventory, delegates permission to Organization
  @GetMapping("/organizations")
  public List<OrganizationDTO> getAllOrganizations(
      @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload) {
    log.debug("REST request to get all Organizations");

    /*
     THE CUSTOMER CHANGED THE RULE. ALL Users will see ALL Organizations.
     
    //Get current authenticated user
    User currentUser = SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneByLogin).orElseThrow();
    
    //Search the PERSON for this user
    Organization person = organizationRepository.findOneByUser(currentUser).orElse(null);
    if (person == null) {
      return Collections.emptyList();
    }
    
    return organizationService.findPersonParentAndChildrenOf(person, OrganizationNature.ORGANIZATION);
    */

    return organizationService.findAllByNature(OrganizationNature.ORGANIZATION, null, null);
  }
}
