package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DesitiRichAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DesitiRichAdesionePfModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DesitiRichAdesionePfCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DesitiRichAdesionePfService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DpianificFerieAmmtoService;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianificFerieAmmto;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiAdesionePfKey;

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

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DesitiRichAdesionePfDto;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DesitiRichAdesionePfWriteDto;
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 = "/desiti-rich-adesione-pf", produces = MediaType.APPLICATION_JSON_VALUE)
public class DesitiRichAdesionePfController extends BaseController<BaseResponse<DesitiRichAdesionePfDto>> {

	/// ENTITY SERVICE
	private final DesitiRichAdesionePfService desitiRichAdesionePfService;
	private final DesitiRichAdesionePfModelAssembler desitiRichAdesionePfModelAssembler;
	private final PagedResourcesAssembler<DesitiRichAdesionePf> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DpianificFerieAmmtoService dpianificFerieAmmtoService;

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DESITI_RICH_ADESIONE_PF_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DesitiRichAdesionePfDto>>> findPaginated(
			DesitiRichAdesionePfCriteria criteria, Pageable pageable) {
		Page<DesitiRichAdesionePf> page = desitiRichAdesionePfService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DesitiRichAdesionePf childMap(DesitiRichAdesionePfWriteDto data) {
		DesitiRichAdesionePf desitiRichAdesionePfToInsert = modelMapper.map(data, DesitiRichAdesionePf.class);
		Collection<DpianificFerieAmmto> theDpianificFerieAmmtos = data.getTheDpianificFerieAmmto().stream()
				.map(element -> modelMapper.map(element, DpianificFerieAmmto.class))
				.peek(element -> element.setTheDesitiRichAdesionePf(desitiRichAdesionePfToInsert))
				.collect(Collectors.toList());
		desitiRichAdesionePfToInsert.setTheDpianificFerieAmmto(theDpianificFerieAmmtos);
		return desitiRichAdesionePfToInsert;
	}

	/**
	 * {@code DELETE  /desiti-rich-adesione-pf/:objectKey} : delete the
	 * desiti-rich-adesione-pf with given objectKey.
	 *
	 * @param objectKey the objectKey of the DesitiRichAdesionePf to delete.
	 * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
	 */
	@DeleteMapping("/{objectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DESITI_RICH_ADESIONE_PF_DELETE.toString())")
	public ResponseEntity<?> delete(@PathVariable String objectKey) {
		desitiRichAdesionePfService
				.deleteById(desitiRichAdesionePfService.findByObjectKey(objectKey).get().getDesitiRichAdesionePfKey());
		return new ResponseEntity<>(new BaseResponse<>(objectKey), HttpStatus.OK);
	}

	/**
	 * GET /the-dstati-adesione-pf_id: Search all DesitiRichAdesionePf for the given
	 * DstatiAdesionePf (parent)
	 * 
	 * @param OK       of DstatiAdesionePf
	 * @param pageable
	 * @return Page of DesitiRichAdesionePf for the given DstatiAdesionePf (parent)
	 */
	@GetMapping("/findByTheDstatiAdesionePf/{dstatiAdesionePfObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DESITI_RICH_ADESIONE_PF_FIND_BY_DSTATI_ADESIONE_PF.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DesitiRichAdesionePfDto>>> findByDstatiAdesionePf(
			@PathVariable String dstatiAdesionePfObjectKey, Pageable pageable) {
		DstatiAdesionePf key = new DstatiAdesionePf(dstatiAdesionePfObjectKey);
		return toResponseEntityPaged(desitiRichAdesionePfService.findByTheDstatiAdesionePf(key, pageable), null);
	}

	/**
	 * GET /the-drich-adesione-pf_id: Search all DesitiRichAdesionePf for the given
	 * DrichAdesionePf (parent)
	 * 
	 * @param OK       of DrichAdesionePf
	 * @param pageable
	 * @return Page of DesitiRichAdesionePf for the given DrichAdesionePf (parent)
	 */
	@GetMapping("/findByTheDrichAdesionePf/{drichAdesionePfObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DESITI_RICH_ADESIONE_PF_FIND_BY_DRICH_ADESIONE_PF.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DesitiRichAdesionePfDto>>> findByDrichAdesionePf(
			@PathVariable String drichAdesionePfObjectKey, Pageable pageable) {
		DrichAdesionePf key = new DrichAdesionePf(drichAdesionePfObjectKey);
		return toResponseEntityPaged(desitiRichAdesionePfService.findByTheDrichAdesionePf(key, pageable), null);
	}

	/**
	 * GET /id/dpianific-ferie-ammto: Search all DpianificFerieAmmto (childs) for
	 * the given DesitiRichAdesionePf
	 * 
	 * @param objectKey ObjectKey of DesitiRichAdesionePf
	 * @param pageable
	 * @return Page of DpianificFerieAmmto for the given DesitiRichAdesionePf
	 */
	@GetMapping("/{objectKey:.+}/dpianific-ferie-ammto")
	@PreAuthorize("hasRole(@permissionHolder.DESITI_RICH_ADESIONE_PF_FIND_BY_THE_DPIANIFIC_FERIE_AMMTO_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DpianificFerieAmmto>> getTheDpianificFerieAmmtoByObjectKey(
			@PathVariable String objectKey, Pageable pageable) {
		DesitiRichAdesionePf desitiRichAdesionePf = new DesitiRichAdesionePf();
		desitiRichAdesionePf.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(dpianificFerieAmmtoService.findByTheDesitiRichAdesionePf(desitiRichAdesionePf, pageable));
	}

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

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

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