package it.micegroup.gestioneferie.libs.assembler;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;

import it.micegroup.gestioneferie.libs.controller.BaseController;
import it.micegroup.gestioneferie.libs.entity.BaseEntity;
import it.micegroup.gestioneferie.libs.response.BaseResponse;

import java.net.URI;

public abstract class BaseModelAssembler<M extends BaseEntity, D extends RepresentationModel<?>, C extends BaseController<BaseResponse<D>>>
		implements RepresentationModelAssembler<M, D> {

	private static ModelMapper modelMapperInstance;

	@Value("${gateway.baseuri}")
	private String baseUri;

	@Autowired
	private ModelMapper modelMapper;

	protected BaseModelAssembler() {
	}

	protected D map(M entity, Class<D> dtoClass, Class<C> controllerClass) {
		D dto = modelMapper.map(entity, dtoClass);
		Link selfLink = convert(linkTo(methodOn(controllerClass).getByObjectKey(entity.getObjectKey())).withSelfRel());
		dto.add(selfLink);
		return dto;
	}

	protected Link convert(Link link) {
		return Link.of(convertLink(link.getHref()), link.getRel());
	}

	private String convertLink(String href) {
		URI uri = URI.create(href);
		return baseUri + uri.getPath();
	}

	protected Link getLink(String ms, String entity, String objectKey, LinkRelation relation) {
		return Link.of("http://127.0.0.1:8090" + "/" + ms + "/" + entity + "/" + objectKey).withRel(relation.value());
	}

}

