package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DrichAdesionePfModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DrichAdesionePfCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DrichAdesionePfService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DesitiRichAdesionePfService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DsollecitiPfService;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DesitiRichAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DsollecitiPf;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianiFerie;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichAdesionePfKey;

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

	/// ENTITY SERVICE
	private final DrichAdesionePfService drichAdesionePfService;
	private final DrichAdesionePfModelAssembler drichAdesionePfModelAssembler;
	private final PagedResourcesAssembler<DrichAdesionePf> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DesitiRichAdesionePfService desitiRichAdesionePfService;
	private final DsollecitiPfService dsollecitiPfService;

	// CONSTRUCTOR
	@PostConstruct
	public void postConstruct() {
		modelMapper.addMappings(new PropertyMap<DrichAdesionePfWriteDto, DrichAdesionePf>() {
			@Override
			protected void configure() {
				skip(destination.getTheDesitiRichAdesionePf());
				skip(destination.getTheDsollecitiPf());
			}
		});
	}

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DRICH_ADESIONE_PF_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DrichAdesionePfDto>>> findPaginated(DrichAdesionePfCriteria criteria,
			Pageable pageable) {
		Page<DrichAdesionePf> page = drichAdesionePfService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DrichAdesionePf childMap(DrichAdesionePfWriteDto data) {
		DrichAdesionePf drichAdesionePfToInsert = modelMapper.map(data, DrichAdesionePf.class);
		Collection<DesitiRichAdesionePf> theDesitiRichAdesionePfs = data.getTheDesitiRichAdesionePf().stream()
				.map(element -> modelMapper.map(element, DesitiRichAdesionePf.class))
				.peek(element -> element.setTheDrichAdesionePf(drichAdesionePfToInsert)).collect(Collectors.toList());
		drichAdesionePfToInsert.setTheDesitiRichAdesionePf(theDesitiRichAdesionePfs);
		Collection<DsollecitiPf> theDsollecitiPfs = data.getTheDsollecitiPf().stream()
				.map(element -> modelMapper.map(element, DsollecitiPf.class))
				.peek(element -> element.setTheDrichAdesionePf(drichAdesionePfToInsert)).collect(Collectors.toList());
		drichAdesionePfToInsert.setTheDsollecitiPf(theDsollecitiPfs);
		return drichAdesionePfToInsert;
	}

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

	/**
	 * GET /the-dstati-rich-adesione-pf_id: Search all DrichAdesionePf for the given
	 * DstatiRichAdesionePf (parent)
	 * 
	 * @param OK       of DstatiRichAdesionePf
	 * @param pageable
	 * @return Page of DrichAdesionePf for the given DstatiRichAdesionePf (parent)
	 */
	@GetMapping("/findByTheDstatiRichAdesionePf/{dstatiRichAdesionePfObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DRICH_ADESIONE_PF_FIND_BY_DSTATI_RICH_ADESIONE_PF.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DrichAdesionePfDto>>> findByDstatiRichAdesionePf(
			@PathVariable String dstatiRichAdesionePfObjectKey, Pageable pageable) {
		DstatiRichAdesionePf key = new DstatiRichAdesionePf(dstatiRichAdesionePfObjectKey);
		return toResponseEntityPaged(drichAdesionePfService.findByTheDstatiRichAdesionePf(key, pageable), null);
	}

	/**
	 * GET /the-dpiani-ferie_id: Search all DrichAdesionePf for the given
	 * DpianiFerie (parent)
	 * 
	 * @param OK       of DpianiFerie
	 * @param pageable
	 * @return Page of DrichAdesionePf for the given DpianiFerie (parent)
	 */
	@GetMapping("/findByTheDpianiFerie/{dpianiFerieObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DRICH_ADESIONE_PF_FIND_BY_DPIANI_FERIE.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DrichAdesionePfDto>>> findByDpianiFerie(
			@PathVariable String dpianiFerieObjectKey, Pageable pageable) {
		DpianiFerie key = new DpianiFerie(dpianiFerieObjectKey);
		return toResponseEntityPaged(drichAdesionePfService.findByTheDpianiFerie(key, pageable), null);
	}

	/**
	 * GET /id/desiti-rich-adesione-pf: Search all DesitiRichAdesionePf (childs) for
	 * the given DrichAdesionePf
	 * 
	 * @param objectKey ObjectKey of DrichAdesionePf
	 * @param pageable
	 * @return Page of DesitiRichAdesionePf for the given DrichAdesionePf
	 */
	@GetMapping("/{objectKey:.+}/desiti-rich-adesione-pf")
	@PreAuthorize("hasRole(@permissionHolder.DRICH_ADESIONE_PF_FIND_BY_THE_DESITI_RICH_ADESIONE_PF_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DesitiRichAdesionePf>> getTheDesitiRichAdesionePfByObjectKey(
			@PathVariable String objectKey, Pageable pageable) {
		DrichAdesionePf drichAdesionePf = new DrichAdesionePf();
		drichAdesionePf.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(desitiRichAdesionePfService.findByTheDrichAdesionePf(drichAdesionePf, pageable));
	}

	/**
	 * GET /id/dsolleciti-pf: Search all DsollecitiPf (childs) for the given
	 * DrichAdesionePf
	 * 
	 * @param objectKey ObjectKey of DrichAdesionePf
	 * @param pageable
	 * @return Page of DsollecitiPf for the given DrichAdesionePf
	 */
	@GetMapping("/{objectKey:.+}/dsolleciti-pf")
	@PreAuthorize("hasRole(@permissionHolder.DRICH_ADESIONE_PF_FIND_BY_THE_DSOLLECITI_PF_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DsollecitiPf>> getTheDsollecitiPfByObjectKey(@PathVariable String objectKey,
			Pageable pageable) {
		DrichAdesionePf drichAdesionePf = new DrichAdesionePf();
		drichAdesionePf.setObjectKey(objectKey);
		return ResponseEntity.ok().body(dsollecitiPfService.findByTheDrichAdesionePf(drichAdesionePf, pageable));
	}

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

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

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