package shina.sample.controller;

import java.net.URI;
import java.util.List;

import shina.sample.dto.PersonDTO;
import org.hibernate.ObjectNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import shina.sample.model.Person;
import shina.sample.service.PersonService;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;

/**
 * Spring REST controller for processing request on Person objects
 * @author ShinaSamuel
 */

@RestController
public class PersonController {

  private final PersonService personService;

  /**
   * Autowired constructor
   *
   * @param personService service {@link PersonService}
   */
  @Autowired
  public PersonController(PersonService personService){
    this.personService = personService;
  }

  /**
   * Registers new {@link Person}
   *
   * @param personDTO {@link PersonDTO}
   * @return object {@link ResponseEntity} with created {@link Person}
   */
  @PostMapping(path = "/api/person", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
  public ResponseEntity<Person> register(@Valid @RequestBody final PersonDTO personDTO) {

    Person person = personService.save(personDTO);
    URI uri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/api/person/{person-id}")
            .buildAndExpand(person.getId()).toUri();
    return ResponseEntity.created(uri).body(person);
  }

  /**
   * Gets all objects {@link Person}
   *
   * @return object {@link ResponseEntity} with collection of all {@link Person}
   */
  @GetMapping(path = "/api/person", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
  public ResponseEntity<List<Person>> getAllPersons() {
    return ResponseEntity.ok(personService.getAll());
  }

  /**
   * Get {@link Person} by id
   *
   * @param personId id of required person
   *
   * @return object {@link ResponseEntity} with required {@link Person}
   */
  @GetMapping(path = "/api/person/{person-id}", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
  public ResponseEntity<Person> getPersonById(@PathVariable(name="person-id") final Long personId) {
    Person person = personService.findById(personId);
    if (person == null) {
      throw new ObjectNotFoundException(personId,"person-id");
    }
    return ResponseEntity.ok(person);
  }
  
}