package org.kar.karusic.api;

import java.util.List;
import java.util.Map;

import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.filter.GenericContext;
import org.kar.karusic.api.UserResourceModel.PartRight;
import org.kar.karusic.api.UserResourceModel.UserMe;
import org.kar.karusic.model.UserKarusic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonInclude;

import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
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.SecurityContext;

@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class);

	@JsonInclude(JsonInclude.Include.NON_NULL)
	public class UserOut {
		public long id;
		public String login;

		public UserOut(final long id, final String login) {
			this.id = id;
			this.login = login;
		}

	}

	public UserResource() {}

	// curl http://localhost:9993/api/users
	@GET
	@RolesAllowed("ADMIN")
	public List<UserKarusic> gets() {
		LOGGER.info("getUsers");
		try {
			return DataAccess.gets(UserKarusic.class);
		} catch (final Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// curl http://localhost:9993/api/users/3
	@GET
	@Path("{id}")
	@RolesAllowed("ADMIN")
	public UserKarusic get(@Context final SecurityContext sc, @PathParam("id") final long userId) {
		LOGGER.info("getUser {}", userId);
		final GenericContext gc = (GenericContext) sc.getUserPrincipal();
		LOGGER.info("===================================================");
		LOGGER.info("== USER {} ", gc.userByToken.name);
		LOGGER.info("===================================================");
		try {
			return DataAccess.get(UserKarusic.class, userId);
		} catch (final Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@GET
	@Path("me")
	@RolesAllowed("USER")
	public UserMe getMe(@Context final SecurityContext sc) {
		LOGGER.debug("getMe()");
		final GenericContext gc = (GenericContext) sc.getUserPrincipal();
		LOGGER.debug("== USER ? {}", gc.userByToken);
		return new UserMe(gc.userByToken.id, gc.userByToken.name, //
				Map.of(gc.userByToken.name, //
						Map.of("admin", PartRight.READ_WRITE, //
								"user", PartRight.READ_WRITE), //
						"karusic", //
						Map.of("user", PartRight.READ)));
	}
}
