package it.micegroup.gestioneferie.configurazionepf.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.configurazionepf.entity.DconfigPaPianiFerie;
import it.micegroup.gestioneferie.configurazionepf.assembler.DconfigPaPianiFerieModelAssembler;
import it.micegroup.gestioneferie.configurazionepf.criteria.DconfigPaPianiFerieCriteria;
import it.micegroup.gestioneferie.configurazionepf.service.DconfigPaPianiFerieService;
import it.micegroup.gestioneferie.configurazionepf.service.DpercAutPianFerieHService;
import it.micegroup.gestioneferie.configurazionepf.service.DconfigPaPfUoHService;
import it.micegroup.gestioneferie.configurazionepf.entity.DpercAutPianFerieH;
import it.micegroup.gestioneferie.configurazionepf.entity.DconfigPaPfUoH;

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.configurazionepf.dto.DconfigPaPianiFerieDto;
import it.micegroup.gestioneferie.configurazionepf.dto.DconfigPaPianiFerieWriteDto;
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 = "/dconfig-pa-piani-ferie", produces = MediaType.APPLICATION_JSON_VALUE)
public class DconfigPaPianiFerieController extends BaseController<BaseResponse<DconfigPaPianiFerieDto>> {

	/// ENTITY SERVICE
	private final DconfigPaPianiFerieService dconfigPaPianiFerieService;
	private final DconfigPaPianiFerieModelAssembler dconfigPaPianiFerieModelAssembler;
	private final PagedResourcesAssembler<DconfigPaPianiFerie> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES
	private final DpercAutPianFerieHService dpercAutPianFerieHService;
	private final DconfigPaPfUoHService dconfigPaPfUoHService;

	// CONSTRUCTOR
	@PostConstruct
	public void postConstruct() {
		modelMapper.addMappings(new PropertyMap<DconfigPaPianiFerieWriteDto, DconfigPaPianiFerie>() {
			@Override
			protected void configure() {
				skip(destination.getTheDpercAutPianFerieH());
				skip(destination.getTheDconfigPaPfUoH());
			}
		});
	}

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DCONFIG_PA_PIANI_FERIE_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DconfigPaPianiFerieDto>>> findPaginated(
			DconfigPaPianiFerieCriteria criteria, Pageable pageable) {
		Page<DconfigPaPianiFerie> page = dconfigPaPianiFerieService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DconfigPaPianiFerie childMap(DconfigPaPianiFerieWriteDto data) {
		DconfigPaPianiFerie dconfigPaPianiFerieToInsert = modelMapper.map(data, DconfigPaPianiFerie.class);
		Collection<DpercAutPianFerieH> theDpercAutPianFerieHs = data.getTheDpercAutPianFerieH().stream()
				.map(element -> modelMapper.map(element, DpercAutPianFerieH.class))
				.peek(element -> element.setTheDconfigPaPianiFerie(dconfigPaPianiFerieToInsert))
				.collect(Collectors.toList());
		dconfigPaPianiFerieToInsert.setTheDpercAutPianFerieH(theDpercAutPianFerieHs);
		Collection<DconfigPaPfUoH> theDconfigPaPfUoHs = data.getTheDconfigPaPfUoH().stream()
				.map(element -> modelMapper.map(element, DconfigPaPfUoH.class))
				.peek(element -> element.setTheDconfigPaPianiFerie(dconfigPaPianiFerieToInsert))
				.collect(Collectors.toList());
		dconfigPaPianiFerieToInsert.setTheDconfigPaPfUoH(theDconfigPaPfUoHs);
		return dconfigPaPianiFerieToInsert;
	}

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

	/**
	 * GET /id/dperc-aut-pian-ferie-h: Search all DpercAutPianFerieH (childs) for
	 * the given DconfigPaPianiFerie
	 * 
	 * @param objectKey ObjectKey of DconfigPaPianiFerie
	 * @param pageable
	 * @return Page of DpercAutPianFerieH for the given DconfigPaPianiFerie
	 */
	@GetMapping("/{objectKey:.+}/dperc-aut-pian-ferie-h")
	@PreAuthorize("hasRole(@permissionHolder.DCONFIG_PA_PIANI_FERIE_FIND_BY_THE_DPERC_AUT_PIAN_FERIE_H_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DpercAutPianFerieH>> getTheDpercAutPianFerieHByObjectKey(@PathVariable String objectKey,
			Pageable pageable) {
		DconfigPaPianiFerie dconfigPaPianiFerie = new DconfigPaPianiFerie();
		dconfigPaPianiFerie.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(dpercAutPianFerieHService.findByTheDconfigPaPianiFerie(dconfigPaPianiFerie, pageable));
	}

	/**
	 * GET /id/dconfig-pa-pf-uo-h: Search all DconfigPaPfUoH (childs) for the given
	 * DconfigPaPianiFerie
	 * 
	 * @param objectKey ObjectKey of DconfigPaPianiFerie
	 * @param pageable
	 * @return Page of DconfigPaPfUoH for the given DconfigPaPianiFerie
	 */
	@GetMapping("/{objectKey:.+}/dconfig-pa-pf-uo-h")
	@PreAuthorize("hasRole(@permissionHolder.DCONFIG_PA_PIANI_FERIE_FIND_BY_THE_DCONFIG_PA_PF_UO_H_OBJECT_KEY.toString())")
	public ResponseEntity<Page<DconfigPaPfUoH>> getTheDconfigPaPfUoHByObjectKey(@PathVariable String objectKey,
			Pageable pageable) {
		DconfigPaPianiFerie dconfigPaPianiFerie = new DconfigPaPianiFerie();
		dconfigPaPianiFerie.setObjectKey(objectKey);
		return ResponseEntity.ok()
				.body(dconfigPaPfUoHService.findByTheDconfigPaPianiFerie(dconfigPaPianiFerie, pageable));
	}

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

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

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