package it.micegroup.gestioneferie.configurazionepf.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.configurazionepf.entity.DregolePianiFeriePk;
import it.micegroup.gestioneferie.configurazionepf.assembler.DregolePianiFeriePkModelAssembler;
import it.micegroup.gestioneferie.configurazionepf.criteria.DregolePianiFeriePkCriteria;
import it.micegroup.gestioneferie.configurazionepf.service.DregolePianiFeriePkService;
import it.micegroup.gestioneferie.configurazionepf.service.DregolePianiFerieHService;
import it.micegroup.gestioneferie.configurazionepf.entity.DregolePianiFerieH;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.configurazionepf.dto.DregolePianiFeriePkDto;
import it.micegroup.gestioneferie.configurazionepf.dto.DregolePianiFeriePkWriteDto;
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-pk", produces = MediaType.APPLICATION_JSON_VALUE)
public class DregolePianiFeriePkController extends BaseController<BaseResponse<DregolePianiFeriePkDto>> {

	/// ENTITY SERVICE
	private final DregolePianiFeriePkService dregolePianiFeriePkService;
	private final DregolePianiFeriePkModelAssembler dregolePianiFeriePkModelAssembler;
	private final PagedResourcesAssembler<DregolePianiFeriePk> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DregolePianiFerieHService dregolePianiFerieHService;

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DREGOLE_PIANI_FERIE_PK_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DregolePianiFeriePkDto>>> findPaginated(
			DregolePianiFeriePkCriteria criteria, Pageable pageable) {
		Page<DregolePianiFeriePk> page = dregolePianiFeriePkService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DregolePianiFeriePk childMap(DregolePianiFeriePkWriteDto data) {
		DregolePianiFeriePk dregolePianiFeriePkToInsert = modelMapper.map(data, DregolePianiFeriePk.class);
		Collection<DregolePianiFerieH> theDregolePianiFerieHs = data.getTheDregolePianiFerieH().stream()
				.map(element -> modelMapper.map(element, DregolePianiFerieH.class))
				.peek(element -> element.setTheDregolePianiFeriePk(dregolePianiFeriePkToInsert))
				.collect(Collectors.toList());
		dregolePianiFeriePkToInsert.setTheDregolePianiFerieH(theDregolePianiFerieHs);
		return dregolePianiFeriePkToInsert;
	}

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

	/**
	 * GET /id/dregole-piani-ferie-h: Search all DregolePianiFerieH (childs) for the
	 * given DregolePianiFeriePk
	 * 
	 * @param objectKey ObjectKey of DregolePianiFeriePk
	 * @param pageable
	 * @return Page of DregolePianiFerieH for the given DregolePianiFeriePk
	 */
	@GetMapping("/{objectKey:.+}/dregole-piani-ferie-h")
	@PreAuthorize("hasRole(@permissionHolder.DREGOLE_PIANI_FERIE_PK_FIND_BY_THE_DREGOLE_PIANI_FERIE_H_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DregolePianiFerieH>> getTheDregolePianiFerieHByObjectKey(@PathVariable String objectKey,
			Pageable pageable) {
		DregolePianiFeriePk dregolePianiFeriePk = new DregolePianiFeriePk();
		dregolePianiFeriePk.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(dregolePianiFerieHService.findByTheDregolePianiFeriePk(dregolePianiFeriePk, pageable));
	}

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

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

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