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

import it.sw.pa.comune.artegna.repository.DisponibilitaRepository;
import it.sw.pa.comune.artegna.service.DisponibilitaService;
import it.sw.pa.comune.artegna.service.dto.DisponibilitaDTO;
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.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.PaginationUtil;
import tech.jhipster.web.util.ResponseUtil;

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

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

    private static final String ENTITY_NAME = "disponibilita";

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

    private final DisponibilitaService disponibilitaService;

    private final DisponibilitaRepository disponibilitaRepository;

    public DisponibilitaResource(DisponibilitaService disponibilitaService, DisponibilitaRepository disponibilitaRepository) {
        this.disponibilitaService = disponibilitaService;
        this.disponibilitaRepository = disponibilitaRepository;
    }

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

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

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

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

    /**
     * {@code PATCH  /disponibilitas/:id} : Partial updates given fields of an existing disponibilita, field will ignore if it is null
     *
     * @param id the id of the disponibilitaDTO to save.
     * @param disponibilitaDTO the disponibilitaDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated disponibilitaDTO,
     * or with status {@code 400 (Bad Request)} if the disponibilitaDTO is not valid,
     * or with status {@code 404 (Not Found)} if the disponibilitaDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the disponibilitaDTO 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<DisponibilitaDTO> partialUpdateDisponibilita(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody DisponibilitaDTO disponibilitaDTO
    ) throws URISyntaxException {
        LOG.debug("REST request to partial update Disponibilita partially : {}, {}", id, disponibilitaDTO);
        if (disponibilitaDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, disponibilitaDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

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

        Optional<DisponibilitaDTO> result = disponibilitaService.partialUpdate(disponibilitaDTO);

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

    /**
     * {@code GET  /disponibilitas} : get all the disponibilitas.
     *
     * @param pageable the pagination information.
     * @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 disponibilitas in body.
     */
    @GetMapping("")
    public ResponseEntity<List<DisponibilitaDTO>> getAllDisponibilitas(
        @org.springdoc.core.annotations.ParameterObject Pageable pageable,
        @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
    ) {
        LOG.debug("REST request to get a page of Disponibilitas");
        Page<DisponibilitaDTO> page;
        if (eagerload) {
            page = disponibilitaService.findAllWithEagerRelationships(pageable);
        } else {
            page = disponibilitaService.findAll(pageable);
        }
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /disponibilitas/:id} : get the "id" disponibilita.
     *
     * @param id the id of the disponibilitaDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the disponibilitaDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<DisponibilitaDTO> getDisponibilita(@PathVariable("id") Long id) {
        LOG.debug("REST request to get Disponibilita : {}", id);
        Optional<DisponibilitaDTO> disponibilitaDTO = disponibilitaService.findOne(id);
        return ResponseUtil.wrapOrNotFound(disponibilitaDTO);
    }

    /**
     * {@code DELETE  /disponibilitas/:id} : delete the "id" disponibilita.
     *
     * @param id the id of the disponibilitaDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDisponibilita(@PathVariable("id") Long id) {
        LOG.debug("REST request to delete Disponibilita : {}", id);
        disponibilitaService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
