package com.wishurgift.entry.controller;

import com.wishurgift.entry.security.Secured;
import com.wishurgift.service.StatisticService;
import com.wishurgift.service.dto.StatisticDTO;
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.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
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("/stats")
@Produces(MediaType.APPLICATION_JSON)
public class StatisticController {

    @Inject
    private StatisticService service;

    @GET
    @Secured
    @Path("/user/{id}")
    public Response stats(@PathParam("id") long id, @Context SecurityContext securityContext) {
        log.info("Begin StatisticController stats, id={}", id);
        // Verification parametre
        if (id < 1) {
            log.info("End StatisticController stats, invalid id");
            return Result.error().data(Result.Error.INVALID_REQUEST).trace(Constant.INVALID_ID).response();
        }
        // Recupération utilisateur connecté
        UserDTO principal = JwtUtils.getUser(securityContext.getUserPrincipal());
        if (principal == null) {
            log.info("End StatisticController stats, unable to get user");
            return Result.error().data(Result.Error.UNABLE_TO_CONNECT).trace(Constant.USER_NOT_FOUND).response();
        }
        // Recuperation statistiques
        StatisticDTO statisticDTO = service.getStatistic(principal, id);
        if (statisticDTO == null) {
            log.info("End StatisticController stats, unable to get data");
            return Result.error().data(Result.Error.UNABLE_TO_GET_DATA).response();
        }
        log.info("End StatisticController stats");
        return Result.success().data(statisticDTO).response();
    }

}
