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

import it.sw.pa.comune.artegna.domain.User;
import it.sw.pa.comune.artegna.repository.ConfermaRepository;
import it.sw.pa.comune.artegna.service.ConfermaQueryService;
import it.sw.pa.comune.artegna.service.ConfermaService;
import it.sw.pa.comune.artegna.service.UserService;
import it.sw.pa.comune.artegna.service.criteria.ConfermaCriteria;
import it.sw.pa.comune.artegna.service.dto.ConfermaDTO;
import it.sw.pa.comune.artegna.service.dto.UtenteAppDTO;
import it.sw.pa.comune.artegna.service.mapper.UserMapper;
import it.sw.pa.comune.artegna.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
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.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
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.Conferma}.
 */
@RestController
@RequestMapping("/api/confermas")
public class ConfermaResource {

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

    private static final String ENTITY_NAME = "conferma";

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

    private final ConfermaService confermaService;

    private final ConfermaRepository confermaRepository;

    private final ConfermaQueryService confermaQueryService;

    private final UserService userService;

    private final UserMapper userMapper;

    public ConfermaResource(
        ConfermaService confermaService,
        ConfermaRepository confermaRepository,
        ConfermaQueryService confermaQueryService,
        UserService userService,
        UserMapper userMapper
    ) {
        this.confermaService = confermaService;
        this.confermaRepository = confermaRepository;
        this.confermaQueryService = confermaQueryService;
        this.userService = userService;
        this.userMapper = userMapper;
    }

    /**
     * {@code POST  /confermas} : Create a new conferma.
     *
     * @param confermaDTO the confermaDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new confermaDTO, or with status {@code 400 (Bad Request)} if the conferma has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("")
    public ResponseEntity<ConfermaDTO> createConferma(@RequestBody ConfermaDTO confermaDTO, @AuthenticationPrincipal UserDetails principal)
        throws URISyntaxException {
        LOG.debug("REST request to save Conferma : {}", confermaDTO);
        /*if (confermaDTO.getId() != null) {
            throw new BadRequestAlertException("A new conferma cannot already have an ID", ENTITY_NAME, "idexists");
        }*/

        String currentLogin = principal.getUsername();
        User currentUser = userService.getUserWithAuthoritiesByLogin(currentLogin).orElseThrow();
        UtenteAppDTO utenteAppDTO = new UtenteAppDTO();
        utenteAppDTO.setInternalUser(userMapper.userToUserDTO(currentUser));
        confermaDTO.setConfermataDa(utenteAppDTO);
        confermaDTO = confermaService.save(confermaDTO);
        return ResponseEntity.created(new URI("/api/confermas/" + confermaDTO.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, confermaDTO.getId().toString()))
            .body(confermaDTO);
    }

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

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

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

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

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

        Optional<ConfermaDTO> result = confermaService.partialUpdate(confermaDTO);

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

    /**
     * {@code GET  /confermas} : get all the confermas.
     *
     * @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 confermas in body.
     */
    @GetMapping("")
    public ResponseEntity<List<ConfermaDTO>> getAllConfermas(
        ConfermaCriteria criteria,
        @org.springdoc.core.annotations.ParameterObject Pageable pageable
    ) {
        LOG.debug("REST request to get Confermas by criteria: {}", criteria);

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

    /**
     * {@code GET  /confermas/count} : count all the confermas.
     *
     * @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> countConfermas(ConfermaCriteria criteria) {
        LOG.debug("REST request to count Confermas by criteria: {}", criteria);
        return ResponseEntity.ok().body(confermaQueryService.countByCriteria(criteria));
    }

    /**
     * {@code GET  /confermas/:id} : get the "id" conferma.
     *
     * @param id the id of the confermaDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the confermaDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<ConfermaDTO> getConferma(@PathVariable("id") Long id) {
        LOG.debug("REST request to get Conferma : {}", id);
        Optional<ConfermaDTO> confermaDTO = confermaService.findOne(id);
        return ResponseUtil.wrapOrNotFound(confermaDTO);
    }

    /**
     * {@code DELETE  /confermas/:id} : delete the "id" conferma.
     *
     * @param id the id of the confermaDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteConferma(@PathVariable("id") Long id) {
        LOG.debug("REST request to delete Conferma : {}", id);
        confermaService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
