package it.sw.pa.comune.artegna.web.rest;

import it.sw.pa.comune.artegna.repository.LiberatoriaRepository;
import it.sw.pa.comune.artegna.service.LiberatoriaService;
import it.sw.pa.comune.artegna.service.dto.LiberatoriaDTO;
import it.sw.pa.comune.artegna.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link it.sw.pa.comune.artegna.domain.Liberatoria}.
 */
@RestController
@RequestMapping("/api/liberatorias")
public class LiberatoriaResource {

    private static final Logger LOG = LoggerFactory.getLogger(LiberatoriaResource.class);

    private static final String ENTITY_NAME = "liberatoria";

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

    private final LiberatoriaService liberatoriaService;

    private final LiberatoriaRepository liberatoriaRepository;

    public LiberatoriaResource(LiberatoriaService liberatoriaService, LiberatoriaRepository liberatoriaRepository) {
        this.liberatoriaService = liberatoriaService;
        this.liberatoriaRepository = liberatoriaRepository;
    }

    /**
     * {@code POST  /liberatorias} : Create a new liberatoria.
     *
     * @param liberatoriaDTO the liberatoriaDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new liberatoriaDTO, or with status {@code 400 (Bad Request)} if the liberatoria has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("")
    public ResponseEntity<LiberatoriaDTO> createLiberatoria(@RequestBody LiberatoriaDTO liberatoriaDTO) throws URISyntaxException {
        LOG.debug("REST request to save Liberatoria : {}", liberatoriaDTO);
        if (liberatoriaDTO.getId() != null) {
            throw new BadRequestAlertException("A new liberatoria cannot already have an ID", ENTITY_NAME, "idexists");
        }
        liberatoriaDTO = liberatoriaService.save(liberatoriaDTO);
        return ResponseEntity.created(new URI("/api/liberatorias/" + liberatoriaDTO.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, liberatoriaDTO.getId().toString()))
            .body(liberatoriaDTO);
    }

    /**
     * {@code PUT  /liberatorias/:id} : Updates an existing liberatoria.
     *
     * @param id the id of the liberatoriaDTO to save.
     * @param liberatoriaDTO the liberatoriaDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated liberatoriaDTO,
     * or with status {@code 400 (Bad Request)} if the liberatoriaDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the liberatoriaDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/{id}")
    public ResponseEntity<LiberatoriaDTO> updateLiberatoria(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody LiberatoriaDTO liberatoriaDTO
    ) throws URISyntaxException {
        LOG.debug("REST request to update Liberatoria : {}, {}", id, liberatoriaDTO);
        if (liberatoriaDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, liberatoriaDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!liberatoriaRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        liberatoriaDTO = liberatoriaService.update(liberatoriaDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, liberatoriaDTO.getId().toString()))
            .body(liberatoriaDTO);
    }

    /**
     * {@code PATCH  /liberatorias/:id} : Partial updates given fields of an existing liberatoria, field will ignore if it is null
     *
     * @param id the id of the liberatoriaDTO to save.
     * @param liberatoriaDTO the liberatoriaDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated liberatoriaDTO,
     * or with status {@code 400 (Bad Request)} if the liberatoriaDTO is not valid,
     * or with status {@code 404 (Not Found)} if the liberatoriaDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the liberatoriaDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<LiberatoriaDTO> partialUpdateLiberatoria(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody LiberatoriaDTO liberatoriaDTO
    ) throws URISyntaxException {
        LOG.debug("REST request to partial update Liberatoria partially : {}, {}", id, liberatoriaDTO);
        if (liberatoriaDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, liberatoriaDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!liberatoriaRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<LiberatoriaDTO> result = liberatoriaService.partialUpdate(liberatoriaDTO);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, liberatoriaDTO.getId().toString())
        );
    }

    /**
     * {@code GET  /liberatorias} : get all the liberatorias.
     *
     * @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 liberatorias in body.
     */
    @GetMapping("")
    public List<LiberatoriaDTO> getAllLiberatorias(
        @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
    ) {
        LOG.debug("REST request to get all Liberatorias");
        return liberatoriaService.findAll();
    }

    /**
     * {@code GET  /liberatorias/:id} : get the "id" liberatoria.
     *
     * @param id the id of the liberatoriaDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the liberatoriaDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<LiberatoriaDTO> getLiberatoria(@PathVariable("id") Long id) {
        LOG.debug("REST request to get Liberatoria : {}", id);
        Optional<LiberatoriaDTO> liberatoriaDTO = liberatoriaService.findOne(id);
        return ResponseUtil.wrapOrNotFound(liberatoriaDTO);
    }

    /**
     * {@code DELETE  /liberatorias/:id} : delete the "id" liberatoria.
     *
     * @param id the id of the liberatoriaDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteLiberatoria(@PathVariable("id") Long id) {
        LOG.debug("REST request to delete Liberatoria : {}", id);
        liberatoriaService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
