package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DstatiRichAdesionePfModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DstatiRichAdesionePfCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DstatiRichAdesionePfService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DrichAdesionePfService;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichAdesionePf;

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

	/// ENTITY SERVICE
	private final DstatiRichAdesionePfService dstatiRichAdesionePfService;
	private final DstatiRichAdesionePfModelAssembler dstatiRichAdesionePfModelAssembler;
	private final PagedResourcesAssembler<DstatiRichAdesionePf> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DrichAdesionePfService drichAdesionePfService;

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_RICH_ADESIONE_PF_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DstatiRichAdesionePfDto>>> findPaginated(
			DstatiRichAdesionePfCriteria criteria, Pageable pageable) {
		Page<DstatiRichAdesionePf> page = dstatiRichAdesionePfService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DstatiRichAdesionePf childMap(DstatiRichAdesionePfWriteDto data) {
		DstatiRichAdesionePf dstatiRichAdesionePfToInsert = modelMapper.map(data, DstatiRichAdesionePf.class);
		Collection<DrichAdesionePf> theDrichAdesionePfs = data.getTheDrichAdesionePf().stream()
				.map(element -> modelMapper.map(element, DrichAdesionePf.class))
				.peek(element -> element.setTheDstatiRichAdesionePf(dstatiRichAdesionePfToInsert))
				.collect(Collectors.toList());
		dstatiRichAdesionePfToInsert.setTheDrichAdesionePf(theDrichAdesionePfs);
		return dstatiRichAdesionePfToInsert;
	}

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

	/**
	 * GET /id/drich-adesione-pf: Search all DrichAdesionePf (childs) for the given
	 * DstatiRichAdesionePf
	 * 
	 * @param objectKey ObjectKey of DstatiRichAdesionePf
	 * @param pageable
	 * @return Page of DrichAdesionePf for the given DstatiRichAdesionePf
	 */
	@GetMapping("/{objectKey:.+}/drich-adesione-pf")
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_RICH_ADESIONE_PF_FIND_BY_THE_DRICH_ADESIONE_PF_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DrichAdesionePf>> getTheDrichAdesionePfByObjectKey(@PathVariable String objectKey,
			Pageable pageable) {
		DstatiRichAdesionePf dstatiRichAdesionePf = new DstatiRichAdesionePf();
		dstatiRichAdesionePf.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(drichAdesionePfService.findByTheDstatiRichAdesionePf(dstatiRichAdesionePf, pageable));
	}

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

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

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