package it.micegroup.gestioneferie.configurazionepf.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.configurazionepf.entity.DregolePianiFerieH;
import it.micegroup.gestioneferie.configurazionepf.assembler.DregolePianiFerieHModelAssembler;
import it.micegroup.gestioneferie.configurazionepf.criteria.DregolePianiFerieHCriteria;
import it.micegroup.gestioneferie.configurazionepf.service.DregolePianiFerieHService;

import it.micegroup.gestioneferie.configurazionepf.entity.DregolePianiFeriePk;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.configurazionepf.dto.DregolePianiFerieHDto;
import it.micegroup.gestioneferie.configurazionepf.dto.DregolePianiFerieHWriteDto;
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 = "/dregole-piani-ferie-h", produces = MediaType.APPLICATION_JSON_VALUE)
public class DregolePianiFerieHController extends BaseController<BaseResponse<DregolePianiFerieHDto>> {

	/// ENTITY SERVICE
	private final DregolePianiFerieHService dregolePianiFerieHService;
	private final DregolePianiFerieHModelAssembler dregolePianiFerieHModelAssembler;
	private final PagedResourcesAssembler<DregolePianiFerieH> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DREGOLE_PIANI_FERIE_H_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DregolePianiFerieHDto>>> findPaginated(
			DregolePianiFerieHCriteria criteria, Pageable pageable) {
		Page<DregolePianiFerieH> page = dregolePianiFerieHService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DregolePianiFerieH childMap(DregolePianiFerieHWriteDto data) {
		DregolePianiFerieH dregolePianiFerieHToInsert = modelMapper.map(data, DregolePianiFerieH.class);
		return dregolePianiFerieHToInsert;
	}

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

	/**
	 * GET /the-dregole-piani-ferie-pk_id: Search all DregolePianiFerieH for the
	 * given DregolePianiFeriePk (parent)
	 * 
	 * @param OK       of DregolePianiFeriePk
	 * @param pageable
	 * @return Page of DregolePianiFerieH for the given DregolePianiFeriePk (parent)
	 */
	@GetMapping("/findByTheDregolePianiFeriePk/{dregolePianiFeriePkObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DREGOLE_PIANI_FERIE_H_FIND_BY_DREGOLE_PIANI_FERIE_PK.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DregolePianiFerieHDto>>> findByDregolePianiFeriePk(
			@PathVariable String dregolePianiFeriePkObjectKey, Pageable pageable) {
		DregolePianiFeriePk key = new DregolePianiFeriePk(dregolePianiFeriePkObjectKey);
		return toResponseEntityPaged(dregolePianiFerieHService.findByTheDregolePianiFeriePk(key, pageable), null);
	}

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

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

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