package com.wishurgift.entry.controller;

import com.wishurgift.entry.security.Connected;
import com.wishurgift.entry.security.Secured;
import com.wishurgift.service.ImageService;
import com.wishurgift.service.dto.ImageDTO;
import com.wishurgift.service.dto.UserDTO;
import com.wishurgift.utils.Constant;
import com.wishurgift.utils.JwtUtils;
import com.wishurgift.wrapper.Result;
import lombok.extern.slf4j.Slf4j;

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

@Slf4j
@Path("/images")
@Produces(MediaType.APPLICATION_JSON)
public class ImageController {

    @Inject
    ImageService service;

    @GET
    @Connected
    @Path("/{id}")
    public Response get(@PathParam("id") long id, @Context SecurityContext securityContext) {
        log.info("Begin ImageController get, id={}", id);
        // Verification données
        if (id < 1) {
            log.info("End ImageController get, invalid id");
            return Result.error().data(Result.Error.INVALID_REQUEST).trace(Constant.INVALID_ID).response();
        }
        // Recup utilisateur connecté
        UserDTO principal = JwtUtils.getUser(securityContext.getUserPrincipal());
        // Recupère l'image
        ImageDTO imageDTO = service.getImage(principal, id);
        if (imageDTO == null) {
            log.info("End ImageController get, unable to get");
            return Result.error().data(Result.Error.UNABLE_TO_GET_DATA).response();
        }
        log.info("End ImageController get");
        return Result.success().data(imageDTO).response();
    }

    @DELETE
    @Secured
    @Path("/{id}")
    public Response delete(@PathParam("id") long id, @Context SecurityContext securityContext) {
        log.info("Begin ImageController delete, id={}", id);
        // Verification données
        if (id < 1) {
            log.info("End ImageController delete, invalid id");
            return Result.error().data(Result.Error.INVALID_REQUEST).trace(Constant.INVALID_ID).response();
        }
        // Recup utilisateur connecté
        UserDTO principal = JwtUtils.getUser(securityContext.getUserPrincipal());
        if (principal == null) {
            log.info("End ImageController delete, unable to connect");
            return Result.error().data(Result.Error.UNABLE_TO_CONNECT).trace(Constant.USER_NOT_FOUND).response();
        }
        // Supprime l'image
        if (service.remove(principal, id)) {
            log.info("End ImageController delete");
            return Result.success().response();
        }
        log.info("End ImageController delete, unauthorized");
        return Result.error().data(Result.Error.UNAUTHORIZED).response();
    }

}
