package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DperiodiAmmtoPf;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DperiodiAmmtoPfModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DperiodiAmmtoPfCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DperiodiAmmtoPfService;

import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianificFerieAmmto;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DpianificFerieAmmtoKey;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DperiodiAmmtoPfDto;
import it.micegroup.gestioneferie.pianificazioneferie.dto.DperiodiAmmtoPfWriteDto;
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 = "/dperiodi-ammto-pf", produces = MediaType.APPLICATION_JSON_VALUE)
public class DperiodiAmmtoPfController extends BaseController<BaseResponse<DperiodiAmmtoPfDto>> {

	/// ENTITY SERVICE
	private final DperiodiAmmtoPfService dperiodiAmmtoPfService;
	private final DperiodiAmmtoPfModelAssembler dperiodiAmmtoPfModelAssembler;
	private final PagedResourcesAssembler<DperiodiAmmtoPf> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DPERIODI_AMMTO_PF_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DperiodiAmmtoPfDto>>> findPaginated(DperiodiAmmtoPfCriteria criteria,
			Pageable pageable) {
		Page<DperiodiAmmtoPf> page = dperiodiAmmtoPfService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DperiodiAmmtoPf childMap(DperiodiAmmtoPfWriteDto data) {
		DperiodiAmmtoPf dperiodiAmmtoPfToInsert = modelMapper.map(data, DperiodiAmmtoPf.class);
		return dperiodiAmmtoPfToInsert;
	}

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

	/**
	 * GET /the-dpianific-ferie-ammto_id: Search all DperiodiAmmtoPf for the given
	 * DpianificFerieAmmto (parent)
	 * 
	 * @param OK       of DpianificFerieAmmto
	 * @param pageable
	 * @return Page of DperiodiAmmtoPf for the given DpianificFerieAmmto (parent)
	 */
	@GetMapping("/findByTheDpianificFerieAmmto/{dpianificFerieAmmtoObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DPERIODI_AMMTO_PF_FIND_BY_DPIANIFIC_FERIE_AMMTO.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DperiodiAmmtoPfDto>>> findByDpianificFerieAmmto(
			@PathVariable String dpianificFerieAmmtoObjectKey, Pageable pageable) {
		DpianificFerieAmmto key = new DpianificFerieAmmto(dpianificFerieAmmtoObjectKey);
		return toResponseEntityPaged(dperiodiAmmtoPfService.findByTheDpianificFerieAmmto(key, pageable), null);
	}

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

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

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