package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichiesteApprovazPf;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DrichiesteApprovazPfModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DrichiesteApprovazPfCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DrichiesteApprovazPfService;

import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichApprovPf;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianiFerie;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiRichApprovPfKey;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DrichiesteApprovazPfDto;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DrichiesteApprovazPfWriteDto;
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 = "/drichieste-approvaz-pf", produces = MediaType.APPLICATION_JSON_VALUE)
public class DrichiesteApprovazPfController extends BaseController<BaseResponse<DrichiesteApprovazPfDto>> {

	/// ENTITY SERVICE
	private final DrichiesteApprovazPfService drichiesteApprovazPfService;
	private final DrichiesteApprovazPfModelAssembler drichiesteApprovazPfModelAssembler;
	private final PagedResourcesAssembler<DrichiesteApprovazPf> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES

	// CONSTRUCTOR
	@PostConstruct
	public void postConstruct() {
	}

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DRICHIESTE_APPROVAZ_PF_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DrichiesteApprovazPfDto>>> findPaginated(
			DrichiesteApprovazPfCriteria criteria, Pageable pageable) {
		Page<DrichiesteApprovazPf> page = drichiesteApprovazPfService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DrichiesteApprovazPf childMap(DrichiesteApprovazPfWriteDto data) {
		DrichiesteApprovazPf drichiesteApprovazPfToInsert = modelMapper.map(data, DrichiesteApprovazPf.class);
		return drichiesteApprovazPfToInsert;
	}

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

	/**
	 * GET /the-dstati-rich-approv-pf_id: Search all DrichiesteApprovazPf for the
	 * given DstatiRichApprovPf (parent)
	 * 
	 * @param OK       of DstatiRichApprovPf
	 * @param pageable
	 * @return Page of DrichiesteApprovazPf for the given DstatiRichApprovPf
	 *         (parent)
	 */
	@GetMapping("/findByTheDstatiRichApprovPf/{dstatiRichApprovPfObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DRICHIESTE_APPROVAZ_PF_FIND_BY_DSTATI_RICH_APPROV_PF.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DrichiesteApprovazPfDto>>> findByDstatiRichApprovPf(
			@PathVariable String dstatiRichApprovPfObjectKey, Pageable pageable) {
		DstatiRichApprovPf key = new DstatiRichApprovPf(dstatiRichApprovPfObjectKey);
		return toResponseEntityPaged(drichiesteApprovazPfService.findByTheDstatiRichApprovPf(key, pageable), null);
	}

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

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

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

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