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

import it.sw.pa.comune.artegna.repository.NotificaRepository;
import it.sw.pa.comune.artegna.service.NotificaQueryService;
import it.sw.pa.comune.artegna.service.NotificaService;
import it.sw.pa.comune.artegna.service.criteria.NotificaCriteria;
import it.sw.pa.comune.artegna.service.dto.NotificaDTO;
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.Notifica}.
 */
@RestController
@RequestMapping("/api/notificas")
public class NotificaResource {

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

    private static final String ENTITY_NAME = "notifica";

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

    private final NotificaService notificaService;

    private final NotificaRepository notificaRepository;

    private final NotificaQueryService notificaQueryService;

    public NotificaResource(
        NotificaService notificaService,
        NotificaRepository notificaRepository,
        NotificaQueryService notificaQueryService
    ) {
        this.notificaService = notificaService;
        this.notificaRepository = notificaRepository;
        this.notificaQueryService = notificaQueryService;
    }

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

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

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

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

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

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

        Optional<NotificaDTO> result = notificaService.partialUpdate(notificaDTO);

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

    /**
     * {@code GET  /notificas} : get all the notificas.
     *
     * @param pageable the pagination information.
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of notificas in body.
     */
    @GetMapping("")
    public ResponseEntity<List<NotificaDTO>> getAllNotificas(
        NotificaCriteria criteria,
        @org.springdoc.core.annotations.ParameterObject Pageable pageable
    ) {
        LOG.debug("REST request to get Notificas by criteria: {}", criteria);

        Page<NotificaDTO> page = notificaQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /notificas/count} : count all the notificas.
     *
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
     */
    @GetMapping("/count")
    public ResponseEntity<Long> countNotificas(NotificaCriteria criteria) {
        LOG.debug("REST request to count Notificas by criteria: {}", criteria);
        return ResponseEntity.ok().body(notificaQueryService.countByCriteria(criteria));
    }

    /**
     * {@code GET  /notificas/:id} : get the "id" notifica.
     *
     * @param id the id of the notificaDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the notificaDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<NotificaDTO> getNotifica(@PathVariable("id") Long id) {
        LOG.debug("REST request to get Notifica : {}", id);
        Optional<NotificaDTO> notificaDTO = notificaService.findOne(id);
        return ResponseUtil.wrapOrNotFound(notificaDTO);
    }

    /**
     * {@code DELETE  /notificas/:id} : delete the "id" notifica.
     *
     * @param id the id of the notificaDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteNotifica(@PathVariable("id") Long id) {
        LOG.debug("REST request to delete Notifica : {}", id);
        notificaService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
