package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DammtiPianiFerie;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DammtiPianiFerieModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DammtiPianiFerieCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DammtiPianiFerieService;

import it.micegroup.gestioneferie.pianificazioneferie.entity.DmotivazioniAlertPf;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianiFerie;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DmotivazioniAlertPfKey;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DammtiPianiFerieDto;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DammtiPianiFerieWriteDto;
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 = "/dammti-piani-ferie", produces = MediaType.APPLICATION_JSON_VALUE)
public class DammtiPianiFerieController extends BaseController<BaseResponse<DammtiPianiFerieDto>> {

	/// ENTITY SERVICE
	private final DammtiPianiFerieService dammtiPianiFerieService;
	private final DammtiPianiFerieModelAssembler dammtiPianiFerieModelAssembler;
	private final PagedResourcesAssembler<DammtiPianiFerie> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DAMMTI_PIANI_FERIE_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DammtiPianiFerieDto>>> findPaginated(
			DammtiPianiFerieCriteria criteria, Pageable pageable) {
		Page<DammtiPianiFerie> page = dammtiPianiFerieService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DammtiPianiFerie childMap(DammtiPianiFerieWriteDto data) {
		DammtiPianiFerie dammtiPianiFerieToInsert = modelMapper.map(data, DammtiPianiFerie.class);
		return dammtiPianiFerieToInsert;
	}

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

	/**
	 * GET /the-dmotivazioni-alert-pf_id: Search all DammtiPianiFerie for the given
	 * DmotivazioniAlertPf (parent)
	 * 
	 * @param OK       of DmotivazioniAlertPf
	 * @param pageable
	 * @return Page of DammtiPianiFerie for the given DmotivazioniAlertPf (parent)
	 */
	@GetMapping("/findByTheDmotivazioniAlertPf/{dmotivazioniAlertPfObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DAMMTI_PIANI_FERIE_FIND_BY_DMOTIVAZIONI_ALERT_PF.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DammtiPianiFerieDto>>> findByDmotivazioniAlertPf(
			@PathVariable String dmotivazioniAlertPfObjectKey, Pageable pageable) {
		DmotivazioniAlertPf key = new DmotivazioniAlertPf(dmotivazioniAlertPfObjectKey);
		return toResponseEntityPaged(dammtiPianiFerieService.findByTheDmotivazioniAlertPf(key, pageable), null);
	}

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

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

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

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