package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DstatiAdesionePfModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DstatiAdesionePfCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DstatiAdesionePfService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DesitiRichAdesionePfService;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DesitiRichAdesionePf;

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

	/// ENTITY SERVICE
	private final DstatiAdesionePfService dstatiAdesionePfService;
	private final DstatiAdesionePfModelAssembler dstatiAdesionePfModelAssembler;
	private final PagedResourcesAssembler<DstatiAdesionePf> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DesitiRichAdesionePfService desitiRichAdesionePfService;

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_ADESIONE_PF_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DstatiAdesionePfDto>>> findPaginated(
			DstatiAdesionePfCriteria criteria, Pageable pageable) {
		Page<DstatiAdesionePf> page = dstatiAdesionePfService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DstatiAdesionePf childMap(DstatiAdesionePfWriteDto data) {
		DstatiAdesionePf dstatiAdesionePfToInsert = modelMapper.map(data, DstatiAdesionePf.class);
		Collection<DesitiRichAdesionePf> theDesitiRichAdesionePfs = data.getTheDesitiRichAdesionePf().stream()
				.map(element -> modelMapper.map(element, DesitiRichAdesionePf.class))
				.peek(element -> element.setTheDstatiAdesionePf(dstatiAdesionePfToInsert)).collect(Collectors.toList());
		dstatiAdesionePfToInsert.setTheDesitiRichAdesionePf(theDesitiRichAdesionePfs);
		return dstatiAdesionePfToInsert;
	}

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

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

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

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

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