package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DstatiPianoFerie;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DstatiPianoFerieModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DstatiPianoFerieCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DstatiPianoFerieService;
import it.micegroup.gestioneferie.pianificazioneferie.service.DpianiFerieService;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianiFerie;

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

	/// ENTITY SERVICE
	private final DstatiPianoFerieService dstatiPianoFerieService;
	private final DstatiPianoFerieModelAssembler dstatiPianoFerieModelAssembler;
	private final PagedResourcesAssembler<DstatiPianoFerie> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DpianiFerieService dpianiFerieService;

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_PIANO_FERIE_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DstatiPianoFerieDto>>> findPaginated(
			DstatiPianoFerieCriteria criteria, Pageable pageable) {
		Page<DstatiPianoFerie> page = dstatiPianoFerieService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DstatiPianoFerie childMap(DstatiPianoFerieWriteDto data) {
		DstatiPianoFerie dstatiPianoFerieToInsert = modelMapper.map(data, DstatiPianoFerie.class);
		Collection<DpianiFerie> theDpianiFeries = data.getTheDpianiFerie().stream()
				.map(element -> modelMapper.map(element, DpianiFerie.class))
				.peek(element -> element.setTheDstatiPianoFerie(dstatiPianoFerieToInsert)).collect(Collectors.toList());
		dstatiPianoFerieToInsert.setTheDpianiFerie(theDpianiFeries);
		return dstatiPianoFerieToInsert;
	}

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

	/**
	 * GET /id/dpiani-ferie: Search all DpianiFerie (childs) for the given
	 * DstatiPianoFerie
	 * 
	 * @param objectKey ObjectKey of DstatiPianoFerie
	 * @param pageable
	 * @return Page of DpianiFerie for the given DstatiPianoFerie
	 */
	@GetMapping("/{objectKey:.+}/dpiani-ferie")
	@PreAuthorize("hasRole(@permissionHolder.DSTATI_PIANO_FERIE_FIND_BY_THE_DPIANI_FERIE_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DpianiFerie>> getTheDpianiFerieByObjectKey(@PathVariable String objectKey,
			Pageable pageable) {
		DstatiPianoFerie dstatiPianoFerie = new DstatiPianoFerie();
		dstatiPianoFerie.setObjectKey(objectKey);
		return ResponseEntity.ok().body(dpianiFerieService.findByTheDstatiPianoFerie(dstatiPianoFerie, pageable));
	}

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

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

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