package de.oaa.xxx.aufgaben;

import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.oaa.xxx.framework.request.RequestChecker;
import jakarta.annotation.Resource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.transaction.SystemException;
import jakarta.transaction.UserTransaction;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriInfo;

@ApplicationScoped
@Path("favorit")
public class FavoritResource {

	private Logger LOGGER = LoggerFactory.getLogger(getClass());
	
	@PersistenceContext(name = "aufgaben")
	private EntityManager entityManager;
	@Resource
	private UserTransaction transaction;
	
	@Path("{favoritId}")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response get(@PathParam("favoritId") UUID favoritId, @Context HttpServletRequest req) throws IllegalStateException, SecurityException, SystemException {
		try {
			RequestChecker.checkRequest(req);
			transaction.begin();
			FavoritEntity entity = new FavoritDAO(entityManager).findById(favoritId);
			if (entity != null) {
				Favorit favorit = entity.toFavorit();
				transaction.commit();
				return Response.ok(favorit).build();
			} else {
				transaction.rollback();
				return Response.noContent().build();
			}
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
			transaction.rollback();
			return Response.serverError().build();
		}
	}

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response all(@Context HttpServletRequest req) throws IllegalStateException, SecurityException, SystemException {
		try {
			UUID userId = RequestChecker.checkRequest(req).getUserId();
			transaction.begin();
			List<FavoritEntity> list = new FavoritDAO(entityManager).getUserFavoriten(userId);
			if (list != null) {
				FavoritList result = new FavoritList();
				result.setFavoriten(list.stream().map(fav -> fav.toFavorit()).toList());
				transaction.commit();
				return Response.ok(result).build();
			} else {
				transaction.rollback();
				return Response.noContent().build();
			}
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
			transaction.rollback();
			return Response.serverError().build();
		}
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response create(Favorit favorit, @Context UriInfo uriInfo, @Context HttpServletRequest req) throws IllegalStateException, SecurityException, SystemException {
		try {
			UUID userId = RequestChecker.checkRequest(req).getUserId();
			if (favorit.getAufgabenGruppeId() == null) {
				return Response.status(Status.BAD_REQUEST).build();
			}
			transaction.begin();
			FavoritDAO dao = new FavoritDAO(entityManager);
			FavoritEntity entity = dao.findByUserAndGruppe(userId, favorit.getAufgabenGruppeId());
			if (entity == null) {
				entity = FavoritEntity.fromFavorit(favorit, userId);
				dao.persist(entity);
			}
			transaction.commit();			
			return Response.created(uriInfo.getAbsolutePathBuilder().path(entity.getFavoritId().toString()).build())
					.build();
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
			transaction.rollback();
			return Response.serverError().build();
		}
	}
	
	@DELETE
	@Consumes(MediaType.APPLICATION_JSON)
	public Response delete(Favorit favorit, @Context HttpServletRequest req) throws IllegalStateException, SecurityException, SystemException {
		try {
			UUID userId = RequestChecker.checkRequest(req).getUserId();
			transaction.begin();
			FavoritDAO dao = new FavoritDAO(entityManager);
			dao.findAllByUserAndGruppe(userId, favorit.getAufgabenGruppeId()).forEach(dao::remove);
			transaction.commit();
			return Response.accepted().build();
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
			transaction.rollback();
			return Response.serverError().build();
		}
	}
}
