package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichiestaPfAmmto;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DstatiRichiestaPfAmmtoModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DstatiRichiestaPfAmmtoCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DstatiRichiestaPfAmmtoService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DrichPianifFerieAmmtoService;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichPianifFerieAmmto;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DstatiRichiestaPfAmmtoDto;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DstatiRichiestaPfAmmtoWriteDto;
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 = "/dstati-richiesta-pf-ammto", produces = MediaType.APPLICATION_JSON_VALUE)
public class DstatiRichiestaPfAmmtoController extends BaseController<BaseResponse<DstatiRichiestaPfAmmtoDto>> {

	/// ENTITY SERVICE
	private final DstatiRichiestaPfAmmtoService dstatiRichiestaPfAmmtoService;
	private final DstatiRichiestaPfAmmtoModelAssembler dstatiRichiestaPfAmmtoModelAssembler;
	private final PagedResourcesAssembler<DstatiRichiestaPfAmmto> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DrichPianifFerieAmmtoService drichPianifFerieAmmtoService;

	// CONSTRUCTOR
	@PostConstruct
	public void postConstruct() {
		modelMapper.addMappings(new PropertyMap<DstatiRichiestaPfAmmtoWriteDto, DstatiRichiestaPfAmmto>() {
			@Override
			protected void configure() {
				skip(destination.getTheDrichPianifFerieAmmto());
			}
		});
	}

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_RICHIESTA_PF_AMMTO_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DstatiRichiestaPfAmmtoDto>>> findPaginated(
			DstatiRichiestaPfAmmtoCriteria criteria, Pageable pageable) {
		Page<DstatiRichiestaPfAmmto> page = dstatiRichiestaPfAmmtoService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DstatiRichiestaPfAmmto childMap(DstatiRichiestaPfAmmtoWriteDto data) {
		DstatiRichiestaPfAmmto dstatiRichiestaPfAmmtoToInsert = modelMapper.map(data, DstatiRichiestaPfAmmto.class);
		Collection<DrichPianifFerieAmmto> theDrichPianifFerieAmmtos = data.getTheDrichPianifFerieAmmto().stream()
				.map(element -> modelMapper.map(element, DrichPianifFerieAmmto.class))
				.peek(element -> element.setTheDstatiRichiestaPfAmmto(dstatiRichiestaPfAmmtoToInsert))
				.collect(Collectors.toList());
		dstatiRichiestaPfAmmtoToInsert.setTheDrichPianifFerieAmmto(theDrichPianifFerieAmmtos);
		return dstatiRichiestaPfAmmtoToInsert;
	}

	/**
	 * {@code DELETE  /dstati-richiesta-pf-ammto/:objectKey} : delete the
	 * dstati-richiesta-pf-ammto with given objectKey.
	 *
	 * @param objectKey the objectKey of the DstatiRichiestaPfAmmto to delete.
	 * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
	 */
	@DeleteMapping("/{objectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_RICHIESTA_PF_AMMTO_DELETE.toString())")
	public ResponseEntity<?> delete(@PathVariable String objectKey) {
		dstatiRichiestaPfAmmtoService.deleteById(
				dstatiRichiestaPfAmmtoService.findByObjectKey(objectKey).get().getDstatiRichiestaPfAmmtoKey());
		return new ResponseEntity<>(new BaseResponse<>(objectKey), HttpStatus.OK);
	}

	/**
	 * GET /id/drich-pianif-ferie-ammto: Search all DrichPianifFerieAmmto (childs)
	 * for the given DstatiRichiestaPfAmmto
	 * 
	 * @param objectKey ObjectKey of DstatiRichiestaPfAmmto
	 * @param pageable
	 * @return Page of DrichPianifFerieAmmto for the given DstatiRichiestaPfAmmto
	 */
	@GetMapping("/{objectKey:.+}/drich-pianif-ferie-ammto")
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_RICHIESTA_PF_AMMTO_FIND_BY_THE_DRICH_PIANIF_FERIE_AMMTO_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DrichPianifFerieAmmto>> getTheDrichPianifFerieAmmtoByObjectKey(
			@PathVariable String objectKey, Pageable pageable) {
		DstatiRichiestaPfAmmto dstatiRichiestaPfAmmto = new DstatiRichiestaPfAmmto();
		dstatiRichiestaPfAmmto.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(drichPianifFerieAmmtoService.findByTheDstatiRichiestaPfAmmto(dstatiRichiestaPfAmmto, pageable));
	}

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

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

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