package it.micegroup.gestioneferie.pianificazioneferie.controller;

import lombok.RequiredArgsConstructor;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DsollecitiPf;
import it.micegroup.gestioneferie.pianificazioneferie.assembler.DsollecitiPfModelAssembler;
import it.micegroup.gestioneferie.pianificazioneferie.criteria.DsollecitiPfCriteria;
import it.micegroup.gestioneferie.pianificazioneferie.service.DsollecitiPfService;

import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichAdesionePf;
import it.micegroup.gestioneferie.pianificazioneferie.entity.DrichAdesionePfKey;

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

	/// ENTITY SERVICE
	private final DsollecitiPfService dsollecitiPfService;
	private final DsollecitiPfModelAssembler dsollecitiPfModelAssembler;
	private final PagedResourcesAssembler<DsollecitiPf> pagedResourcesAssembler;
	private final ModelMapper modelMapper;
	// CHILD SERVICES

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

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

	// API
	@GetMapping
	@PreAuthorize("hasRole(@permissionHolder.DSOLLECITI_PF_FIND_PAGINATED.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DsollecitiPfDto>>> findPaginated(DsollecitiPfCriteria criteria,
			Pageable pageable) {
		Page<DsollecitiPf> page = dsollecitiPfService.findByCriteria(criteria, pageable);
		return toResponseEntityPaged(page, null);
	}

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

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

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

	private DsollecitiPf childMap(DsollecitiPfWriteDto data) {
		DsollecitiPf dsollecitiPfToInsert = modelMapper.map(data, DsollecitiPf.class);
		return dsollecitiPfToInsert;
	}

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

	/**
	 * GET /the-drich-adesione-pf_id: Search all DsollecitiPf for the given
	 * DrichAdesionePf (parent)
	 * 
	 * @param OK       of DrichAdesionePf
	 * @param pageable
	 * @return Page of DsollecitiPf for the given DrichAdesionePf (parent)
	 */
	@GetMapping("/findByTheDrichAdesionePf/{drichAdesionePfObjectKey:.+}")
	@PreAuthorize("hasRole(@permissionHolder.DSOLLECITI_PF_FIND_BY_DRICH_ADESIONE_PF.toString())")
	public ResponseEntity<BaseResponse<PagedModel<DsollecitiPfDto>>> findByDrichAdesionePf(
			@PathVariable String drichAdesionePfObjectKey, Pageable pageable) {
		DrichAdesionePf key = new DrichAdesionePf(drichAdesionePfObjectKey);
		return toResponseEntityPaged(dsollecitiPfService.findByTheDrichAdesionePf(key, pageable), null);
	}

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

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

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