package org.kar.karideo.api;

import java.util.List;

import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.filter.GenericContext;
import org.kar.karideo.model.UserKarideo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonInclude;

import io.swagger.v3.oas.annotations.Operation;
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 {
	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")
	@Operation(description = "Get all the users", tags = "SYSTEM")
	public List<UserKarideo> gets() {
		System.out.println("getUsers");
		try {
			return DataAccess.gets(UserKarideo.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")
	@Operation(description = "Get a specific user data", tags = "SYSTEM")
	public UserKarideo get(@Context final SecurityContext sc, @PathParam("id") final long userId) {
		System.out.println("getUser " + userId);
		final GenericContext gc = (GenericContext) sc.getUserPrincipal();
		System.out.println("===================================================");
		System.out.println("== USER ? " + gc.userByToken.name);
		System.out.println("===================================================");
		try {
			return DataAccess.get(UserKarideo.class, userId);
		} catch (final Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@GET
	@Path("me")
	@RolesAllowed("USER")
	@Operation(description = "Get the user personal data", tags = "SYSTEM")
	public UserOut getMe(@Context final SecurityContext sc) {
		LOGGER.debug("getMe()");
		final GenericContext gc = (GenericContext) sc.getUserPrincipal();
		LOGGER.debug("== USER ? {}", gc.userByToken);
		return new UserOut(gc.userByToken.id, gc.userByToken.name);
	}

}
