package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichPianifFerieAmmto;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DrichPianifFerieAmmtoModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DrichPianifFerieAmmtoCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DrichPianifFerieAmmtoService;

import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichiestaPfAmmto;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianificFerieAmmto;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichiestaPfAmmtoKey;

import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianificFerieAmmtoKey;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DrichPianifFerieAmmtoDto;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DrichPianifFerieAmmtoWriteDto;
import it.micegroup.gestioneferie.libs.response.BaseResponse;
import it.micegroup.gestioneferie.libs.request.BaseRequest;
import javax.annotation.PostConstruct;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.PagedModel;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;
import java.util.Locale;
import java.util.Optional;

import java.util.Collection;
import org.modelmapper.PropertyMap;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/drich-pianif-ferie-ammto", produces = MediaType.APPLICATION_JSON_VALUE)
public class DrichPianifFerieAmmtoController extends BaseController<BaseResponse<DrichPianifFerieAmmtoDto>> {

	/// ENTITY SERVICE
	private final DrichPianifFerieAmmtoService drichPianifFerieAmmtoService;
	private final DrichPianifFerieAmmtoModelAssembler drichPianifFerieAmmtoModelAssembler;
	private final PagedResourcesAssembler<DrichPianifFerieAmmto> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES

	// CONSTRUCTOR
	@PostConstruct
	public void postConstruct() {
	}

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LogManager.getLogger(DrichPianifFerieAmmtoController.class);

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DRICH_PIANIF_FERIE_AMMTO_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DrichPianifFerieAmmtoDto>>> findPaginated(
			DrichPianifFerieAmmtoCriteria criteria, Pageable pageable) {
		Page<DrichPianifFerieAmmto> page = drichPianifFerieAmmtoService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

	/**
	 * {@code GET  /drich-pianif-ferie-ammto/:objectKey} : get the
	 * drich-pianif-ferie-ammto with given objectKey.
	 *
	 * @param objectKey the objectKey of the drich-pianif-ferie-ammto to retrieve.
	 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body
	 *         the drich-pianif-ferie-ammto, or with status {@code 404 (Not Found)}.
	 */
	@GetMapping("/{objectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DRICH_PIANIF_FERIE_AMMTO_FIND_BY_ID.toString())")
	public ResponseEntity<BaseResponse<DrichPianifFerieAmmtoDto>> getByObjectKey(@PathVariable String objectKey) {
		return toResponseEntity(drichPianifFerieAmmtoService.findByObjectKey(objectKey), null, HttpStatus.OK);
	}

	/**
	 * {@code PUT  /drich-pianif-ferie-ammto} : Updates an existing
	 * DrichPianifFerieAmmto.
	 *
	 * @param DrichPianifFerieAmmto the DrichPianifFerieAmmto to update.
	 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body
	 *         the updated DrichPianifFerieAmmto, or with status
	 *         {@code 400 (Bad Request)} if the DrichPianifFerieAmmto is not valid,
	 *         or with status {@code 500 (Internal Server Error)} if the
	 *         DrichPianifFerieAmmto couldn't be updated.
	 */
	@PutMapping
	@PreAuthorize("hasRole(@permissionHolder.DRICH_PIANIF_FERIE_AMMTO_UPDATE.toString())")
	public ResponseEntity<?> update(@Valid @RequestBody BaseRequest<DrichPianifFerieAmmtoWriteDto> request) {
		return toResponseEntity(
				Optional.of(drichPianifFerieAmmtoService
						.bulkUpdate(modelMapper.map(request.getData(), DrichPianifFerieAmmto.class))),
				null, HttpStatus.OK);
	}

	/**
	 * {@code POST  /drich-pianif-ferie-ammto} : Create a new DrichPianifFerieAmmto.
	 *
	 * @param DrichPianifFerieAmmto the DrichPianifFerieAmmto to create.
	 * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with
	 *         body the new DrichPianifFerieAmmto, or with status
	 *         {@code 400 (Bad Request)} if the DrichPianifFerieAmmto has already an
	 *         ID.
	 * @throws URISyntaxException if the Location URI syntax is incorrect.
	 */
	@PostMapping
	@PreAuthorize("hasRole(@permissionHolder.DRICH_PIANIF_FERIE_AMMTO_CREATE.toString())")
	public ResponseEntity<?> save(@Valid @RequestBody BaseRequest<DrichPianifFerieAmmtoWriteDto> request) {
		ResponseEntity<?> response = null;
		DrichPianifFerieAmmto drichPianifFerieAmmtoToInsert = childMap(request.getData());
		try {
			DrichPianifFerieAmmto newDrichPianifFerieAmmto = drichPianifFerieAmmtoService
					.insert(modelMapper.map(drichPianifFerieAmmtoToInsert, DrichPianifFerieAmmto.class));
			URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
					.buildAndExpand(newDrichPianifFerieAmmto.getDrichPianifFerieAmmtoKey()).toUri();
			HttpHeaders headers = new HttpHeaders();
			headers.setLocation(location);
			response = toResponseEntity(Optional.of(newDrichPianifFerieAmmto), headers, HttpStatus.CREATED);
		} catch (Exception exception) {
			LOGGER.error("Exception:", exception);
		}
		return response;
	}

	private DrichPianifFerieAmmto childMap(DrichPianifFerieAmmtoWriteDto data) {
		DrichPianifFerieAmmto drichPianifFerieAmmtoToInsert = modelMapper.map(data, DrichPianifFerieAmmto.class);
		return drichPianifFerieAmmtoToInsert;
	}

	/**
	 * {@code DELETE  /drich-pianif-ferie-ammto/:objectKey} : delete the
	 * drich-pianif-ferie-ammto with given objectKey.
	 *
	 * @param objectKey the objectKey of the DrichPianifFerieAmmto to delete.
	 * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
	 */
	@DeleteMapping("/{objectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DRICH_PIANIF_FERIE_AMMTO_DELETE.toString())")
	public ResponseEntity<?> delete(@PathVariable String objectKey) {
		drichPianifFerieAmmtoService.deleteById(
				drichPianifFerieAmmtoService.findByObjectKey(objectKey).get().getDrichPianifFerieAmmtoKey());
		return new ResponseEntity<>(new BaseResponse<>(objectKey), HttpStatus.OK);
	}

	/**
	 * GET /the-dstati-richiesta-pf-ammto_id: Search all DrichPianifFerieAmmto for
	 * the given DstatiRichiestaPfAmmto (parent)
	 * 
	 * @param OK       of DstatiRichiestaPfAmmto
	 * @param pageable
	 * @return Page of DrichPianifFerieAmmto for the given DstatiRichiestaPfAmmto
	 *         (parent)
	 */
	@GetMapping("/findByTheDstatiRichiestaPfAmmto/{dstatiRichiestaPfAmmtoObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DRICH_PIANIF_FERIE_AMMTO_FIND_BY_DSTATI_RICHIESTA_PF_AMMTO.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DrichPianifFerieAmmtoDto>>> findByDstatiRichiestaPfAmmto(
			@PathVariable String dstatiRichiestaPfAmmtoObjectKey, Pageable pageable) {
		DstatiRichiestaPfAmmto key = new DstatiRichiestaPfAmmto(dstatiRichiestaPfAmmtoObjectKey);
		return toResponseEntityPaged(drichPianifFerieAmmtoService.findByTheDstatiRichiestaPfAmmto(key, pageable), null);
	}

	/**
	 * GET /the-dpianific-ferie-ammto_id: Search all DrichPianifFerieAmmto for the
	 * given DpianificFerieAmmto (parent)
	 * 
	 * @param OK       of DpianificFerieAmmto
	 * @param pageable
	 * @return Page of DrichPianifFerieAmmto for the given DpianificFerieAmmto
	 *         (parent)
	 */
	@GetMapping("/findByTheDpianificFerieAmmto/{dpianificFerieAmmtoObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DRICH_PIANIF_FERIE_AMMTO_FIND_BY_DPIANIFIC_FERIE_AMMTO.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DrichPianifFerieAmmtoDto>>> findByDpianificFerieAmmto(
			@PathVariable String dpianificFerieAmmtoObjectKey, Pageable pageable) {
		DpianificFerieAmmto key = new DpianificFerieAmmto(dpianificFerieAmmtoObjectKey);
		return toResponseEntityPaged(drichPianifFerieAmmtoService.findByTheDpianificFerieAmmto(key, pageable), null);
	}

	private ResponseEntity<BaseResponse<DrichPianifFerieAmmtoDto>> toResponseEntity(
			Optional<DrichPianifFerieAmmto> maybeResponse, HttpHeaders header, HttpStatus status) {
		return maybeResponse
				.map(response -> new ResponseEntity<>(
						new BaseResponse<>(drichPianifFerieAmmtoModelAssembler.toModel(response)), header, status))
				.orElseThrow(() -> new NotFoundException(DrichPianifFerieAmmto.class, new Locale("it")));
	}

	private ResponseEntity<BaseResponse<PagedModel<DrichPianifFerieAmmtoDto>>> toResponseEntityPaged(
			Page<DrichPianifFerieAmmto> list, HttpHeaders header) {
		BaseResponse<PagedModel<DrichPianifFerieAmmtoDto>> collModel = new BaseResponse<>(
				pagedResourcesAssembler.toModel(list, drichPianifFerieAmmtoModelAssembler));
		return ResponseEntity.ok().headers(header).body(collModel);
	}

	@SuppressWarnings("unused")
	private DrichPianifFerieAmmto dtoToEntity(DrichPianifFerieAmmtoDto dto) {
		return new ModelMapper().map(dto, DrichPianifFerieAmmto.class);
	}
}
