package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiPianificFerie;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DstatiPianificFerieModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DstatiPianificFerieCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DstatiPianificFerieService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DpianificFerieAmmtoService;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianificFerieAmmto;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DstatiPianificFerieDto;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DstatiPianificFerieWriteDto;
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-pianific-ferie", produces = MediaType.APPLICATION_JSON_VALUE)
public class DstatiPianificFerieController extends BaseController<BaseResponse<DstatiPianificFerieDto>> {

	/// ENTITY SERVICE
	private final DstatiPianificFerieService dstatiPianificFerieService;
	private final DstatiPianificFerieModelAssembler dstatiPianificFerieModelAssembler;
	private final PagedResourcesAssembler<DstatiPianificFerie> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DpianificFerieAmmtoService dpianificFerieAmmtoService;

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_PIANIFIC_FERIE_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DstatiPianificFerieDto>>> findPaginated(
			DstatiPianificFerieCriteria criteria, Pageable pageable) {
		Page<DstatiPianificFerie> page = dstatiPianificFerieService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DstatiPianificFerie childMap(DstatiPianificFerieWriteDto data) {
		DstatiPianificFerie dstatiPianificFerieToInsert = modelMapper.map(data, DstatiPianificFerie.class);
		Collection<DpianificFerieAmmto> theDpianificFerieAmmtos = data.getTheDpianificFerieAmmto().stream()
				.map(element -> modelMapper.map(element, DpianificFerieAmmto.class))
				.peek(element -> element.setTheDstatiPianificFerie(dstatiPianificFerieToInsert))
				.collect(Collectors.toList());
		dstatiPianificFerieToInsert.setTheDpianificFerieAmmto(theDpianificFerieAmmtos);
		return dstatiPianificFerieToInsert;
	}

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

	/**
	 * GET /id/dpianific-ferie-ammto: Search all DpianificFerieAmmto (childs) for
	 * the given DstatiPianificFerie
	 * 
	 * @param objectKey ObjectKey of DstatiPianificFerie
	 * @param pageable
	 * @return Page of DpianificFerieAmmto for the given DstatiPianificFerie
	 */
	@GetMapping("/{objectKey:.+}/dpianific-ferie-ammto")
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_PIANIFIC_FERIE_FIND_BY_THE_DPIANIFIC_FERIE_AMMTO_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DpianificFerieAmmto>> getTheDpianificFerieAmmtoByObjectKey(
			@PathVariable String objectKey, Pageable pageable) {
		DstatiPianificFerie dstatiPianificFerie = new DstatiPianificFerie();
		dstatiPianificFerie.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(dpianificFerieAmmtoService.findByTheDstatiPianificFerie(dstatiPianificFerie, pageable));
	}

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

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

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