package de.oaa.xxx.aufgaben;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;

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

import jakarta.annotation.Resource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.UserTransaction;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;

@ApplicationScoped
@Path("fill")
public class FillerResource {
	
	private Logger LOGGER = LoggerFactory.getLogger(getClass());
	
	@PersistenceContext(name = "aufgaben")
	private EntityManager entityManager;
	@Resource
	private UserTransaction transaction;
	
	@GET
	public Response fill() {
		try {
			transaction.begin();
			DefaultFiller filler = new DefaultFiller(entityManager);
			filler.chastityFemale();
			filler.chastityMale();
			filler.plugs();
			filler.knebel();
			filler.stafen();
			filler.aufgaben();
			transaction.commit();
			return Response.ok().build();
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
			return Response.serverError().build();
		}
	}
	
	@GET
	@Path("read")
	public Response read() throws IOException, NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
		AufgabenGruppeList result = ClientBuilder.newClient().target("http://localhost:8080/aufgaben-service/gruppe/all").request().get(AufgabenGruppeList.class);
		

		new File("C:/test/").mkdirs();
		for (AufgabenGruppeDisplay entity : result.getGruppen()) {
			Files.write(new File("C:/test/" + entity.getName() + ".png").toPath(), Base64.getDecoder().decode(entity.getBild()));
		}
		
		return Response.ok().build();
	}
}
