package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichApprovPf;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DstatiRichApprovPfModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DstatiRichApprovPfCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DstatiRichApprovPfService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DrichiesteApprovazPfService;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichiesteApprovazPf;

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

	/// ENTITY SERVICE
	private final DstatiRichApprovPfService dstatiRichApprovPfService;
	private final DstatiRichApprovPfModelAssembler dstatiRichApprovPfModelAssembler;
	private final PagedResourcesAssembler<DstatiRichApprovPf> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DrichiesteApprovazPfService drichiesteApprovazPfService;

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_RICH_APPROV_PF_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DstatiRichApprovPfDto>>> findPaginated(
			DstatiRichApprovPfCriteria criteria, Pageable pageable) {
		Page<DstatiRichApprovPf> page = dstatiRichApprovPfService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DstatiRichApprovPf childMap(DstatiRichApprovPfWriteDto data) {
		DstatiRichApprovPf dstatiRichApprovPfToInsert = modelMapper.map(data, DstatiRichApprovPf.class);
		Collection<DrichiesteApprovazPf> theDrichiesteApprovazPfs = data.getTheDrichiesteApprovazPf().stream()
				.map(element -> modelMapper.map(element, DrichiesteApprovazPf.class))
				.peek(element -> element.setTheDstatiRichApprovPf(dstatiRichApprovPfToInsert))
				.collect(Collectors.toList());
		dstatiRichApprovPfToInsert.setTheDrichiesteApprovazPf(theDrichiesteApprovazPfs);
		return dstatiRichApprovPfToInsert;
	}

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

	/**
	 * GET /id/drichieste-approvaz-pf: Search all DrichiesteApprovazPf (childs) for
	 * the given DstatiRichApprovPf
	 * 
	 * @param objectKey ObjectKey of DstatiRichApprovPf
	 * @param pageable
	 * @return Page of DrichiesteApprovazPf for the given DstatiRichApprovPf
	 */
	@GetMapping("/{objectKey:.+}/drichieste-approvaz-pf")
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_RICH_APPROV_PF_FIND_BY_THE_DRICHIESTE_APPROVAZ_PF_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DrichiesteApprovazPf>> getTheDrichiesteApprovazPfByObjectKey(
			@PathVariable String objectKey, Pageable pageable) {
		DstatiRichApprovPf dstatiRichApprovPf = new DstatiRichApprovPf();
		dstatiRichApprovPf.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(drichiesteApprovazPfService.findByTheDstatiRichApprovPf(dstatiRichApprovPf, pageable));
	}

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

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

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