package it.micegroup.gestioneferie.configurazionepf.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.configurazionepf.entity.DconfigPaPfUoH;
import it.micegroup.gestioneferie.configurazionepf.assembler.DconfigPaPfUoHModelAssembler;
import it.micegroup.gestioneferie.configurazionepf.criteria.DconfigPaPfUoHCriteria;
import it.micegroup.gestioneferie.configurazionepf.service.DconfigPaPfUoHService;

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

import it.micegroup.voila2runtime.exception.*;
import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.configurazionepf.dto.DconfigPaPfUoHDto;
import it.micegroup.gestioneferie.configurazionepf.dto.DconfigPaPfUoHWriteDto;
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-pf-uo-h", produces = MediaType.APPLICATION_JSON_VALUE)
public class DconfigPaPfUoHController extends BaseController<BaseResponse<DconfigPaPfUoHDto>> {

	/// ENTITY SERVICE
	private final DconfigPaPfUoHService dconfigPaPfUoHService;
	private final DconfigPaPfUoHModelAssembler dconfigPaPfUoHModelAssembler;
	private final PagedResourcesAssembler<DconfigPaPfUoH> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DCONFIG_PA_PF_UO_H_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DconfigPaPfUoHDto>>> findPaginated(DconfigPaPfUoHCriteria criteria,
			Pageable pageable) {
		Page<DconfigPaPfUoH> page = dconfigPaPfUoHService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DconfigPaPfUoH childMap(DconfigPaPfUoHWriteDto data) {
		DconfigPaPfUoH dconfigPaPfUoHToInsert = modelMapper.map(data, DconfigPaPfUoH.class);
		return dconfigPaPfUoHToInsert;
	}

	/**
	 * {@code DELETE  /dconfig-pa-pf-uo-h/:objectKey} : delete the
	 * dconfig-pa-pf-uo-h with given objectKey.
	 *
	 * @param objectKey the objectKey of the DconfigPaPfUoH to delete.
	 * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
	 */
	@DeleteMapping("/{objectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DCONFIG_PA_PF_UO_H_DELETE.toString())")
	public ResponseEntity<?> delete(@PathVariable String objectKey) {
		dconfigPaPfUoHService
				.deleteById(dconfigPaPfUoHService.findByObjectKey(objectKey).get().getSequIdConfigPaPfUoH());
		return new ResponseEntity<>(new BaseResponse<>(objectKey), HttpStatus.OK);
	}

	/**
	 * GET /the-dconfig-pa-piani-ferie_id: Search all DconfigPaPfUoH for the given
	 * DconfigPaPianiFerie (parent)
	 * 
	 * @param OK       of DconfigPaPianiFerie
	 * @param pageable
	 * @return Page of DconfigPaPfUoH for the given DconfigPaPianiFerie (parent)
	 */
	@GetMapping("/findByTheDconfigPaPianiFerie/{dconfigPaPianiFerieObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DCONFIG_PA_PF_UO_H_FIND_BY_DCONFIG_PA_PIANI_FERIE.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DconfigPaPfUoHDto>>> findByDconfigPaPianiFerie(
			@PathVariable String dconfigPaPianiFerieObjectKey, Pageable pageable) {
		DconfigPaPianiFerie key = new DconfigPaPianiFerie(dconfigPaPianiFerieObjectKey);
		return toResponseEntityPaged(dconfigPaPfUoHService.findByTheDconfigPaPianiFerie(key, pageable), null);
	}

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

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

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