package it.micegroup.gestioneferie.configurazionepf.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.configurazionepf.entity.DpercAutPianFeriePk;
import it.micegroup.gestioneferie.configurazionepf.assembler.DpercAutPianFeriePkModelAssembler;
import it.micegroup.gestioneferie.configurazionepf.criteria.DpercAutPianFeriePkCriteria;
import it.micegroup.gestioneferie.configurazionepf.service.DpercAutPianFeriePkService;
import it.micegroup.gestioneferie.configurazionepf.service.DpercAutPianFerieHService;
import it.micegroup.gestioneferie.configurazionepf.entity.DpercAutPianFerieH;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.configurazionepf.dto.DpercAutPianFeriePkDto;
import it.micegroup.gestioneferie.configurazionepf.dto.DpercAutPianFeriePkWriteDto;
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 = "/dperc-aut-pian-ferie-pk", produces = MediaType.APPLICATION_JSON_VALUE)
public class DpercAutPianFeriePkController extends BaseController<BaseResponse<DpercAutPianFeriePkDto>> {

	/// ENTITY SERVICE
	private final DpercAutPianFeriePkService dpercAutPianFeriePkService;
	private final DpercAutPianFeriePkModelAssembler dpercAutPianFeriePkModelAssembler;
	private final PagedResourcesAssembler<DpercAutPianFeriePk> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DpercAutPianFerieHService dpercAutPianFerieHService;

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DPERC_AUT_PIAN_FERIE_PK_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DpercAutPianFeriePkDto>>> findPaginated(
			DpercAutPianFeriePkCriteria criteria, Pageable pageable) {
		Page<DpercAutPianFeriePk> page = dpercAutPianFeriePkService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DpercAutPianFeriePk childMap(DpercAutPianFeriePkWriteDto data) {
		DpercAutPianFeriePk dpercAutPianFeriePkToInsert = modelMapper.map(data, DpercAutPianFeriePk.class);
		Collection<DpercAutPianFerieH> theDpercAutPianFerieHs = data.getTheDpercAutPianFerieH().stream()
				.map(element -> modelMapper.map(element, DpercAutPianFerieH.class))
				.peek(element -> element.setTheDpercAutPianFeriePk(dpercAutPianFeriePkToInsert))
				.collect(Collectors.toList());
		dpercAutPianFeriePkToInsert.setTheDpercAutPianFerieH(theDpercAutPianFerieHs);
		return dpercAutPianFeriePkToInsert;
	}

	/**
	 * {@code DELETE  /dperc-aut-pian-ferie-pk/:objectKey} : delete the
	 * dperc-aut-pian-ferie-pk with given objectKey.
	 *
	 * @param objectKey the objectKey of the DpercAutPianFeriePk to delete.
	 * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
	 */
	@DeleteMapping("/{objectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DPERC_AUT_PIAN_FERIE_PK_DELETE.toString())")
	public ResponseEntity<?> delete(@PathVariable String objectKey) {
		dpercAutPianFeriePkService
				.deleteById(dpercAutPianFeriePkService.findByObjectKey(objectKey).get().getSequIdPercAutPianFeriePk());
		return new ResponseEntity<>(new BaseResponse<>(objectKey), HttpStatus.OK);
	}

	/**
	 * GET /id/dperc-aut-pian-ferie-h: Search all DpercAutPianFerieH (childs) for
	 * the given DpercAutPianFeriePk
	 * 
	 * @param objectKey ObjectKey of DpercAutPianFeriePk
	 * @param pageable
	 * @return Page of DpercAutPianFerieH for the given DpercAutPianFeriePk
	 */
	@GetMapping("/{objectKey:.+}/dperc-aut-pian-ferie-h")
	@PreAuthorize("hasRole(@permissionHolder.DPERC_AUT_PIAN_FERIE_PK_FIND_BY_THE_DPERC_AUT_PIAN_FERIE_H_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DpercAutPianFerieH>> getTheDpercAutPianFerieHByObjectKey(@PathVariable String objectKey,
			Pageable pageable) {
		DpercAutPianFeriePk dpercAutPianFeriePk = new DpercAutPianFeriePk();
		dpercAutPianFeriePk.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(dpercAutPianFerieHService.findByTheDpercAutPianFeriePk(dpercAutPianFeriePk, pageable));
	}

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

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

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