package org.exoplatform.cs.rest;

import io.swagger.annotations.*;

import org.exoplatform.common.http.HTTPStatus;
import org.exoplatform.cs.dto.EnvironmentDTO;
import org.exoplatform.cs.dto.SpaceDTO;
import org.exoplatform.cs.rest.model.CSUserSettings;
import org.exoplatform.cs.rest.utils.CSRestUtils;
import org.exoplatform.cs.rest.utils.EntityBuilder;
import org.exoplatform.cs.service.CSSpaceService;
import org.exoplatform.cs.service.EnvironmentService;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.User;
import org.exoplatform.services.rest.resource.ResourceContainer;
import org.exoplatform.services.security.ConversationState;
import org.exoplatform.social.core.space.spi.SpaceService;

import javax.annotation.security.RolesAllowed;
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.MediaType;
import javax.ws.rs.core.Response;


@Path("/customer-space/space")
@Api(value = "/customer-space/space", description = "Manages customer space information")
public class CustomerSpaceRest implements ResourceContainer {
    private CSSpaceService csSpaceService;
    private EnvironmentService environmentService;

    private static final String SPACE_GROUP = "/spaces/";
    private static final Log LOG = ExoLogger.getLogger(CustomerSpaceRest.class);


    public CustomerSpaceRest (CSSpaceService csSpaceService, EnvironmentService environmentService) {
        this.csSpaceService = csSpaceService;
        this.environmentService = environmentService;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/environment/{id}")
    @RolesAllowed("users")
    @ApiOperation(
            value = "retrieves a space environment",
            httpMethod = "GET", response = Response.class, produces = "application/json"
    )
    @ApiResponses(
            value = {@ApiResponse(code = HTTPStatus.OK, message = "Request fulfilled"),
                    @ApiResponse(code = HTTPStatus.UNAUTHORIZED, message = "Unauthorized operation"),
                    @ApiResponse(code = HTTPStatus.INTERNAL_ERROR, message = "Internal server error"),}
    )
    public Response getEnvironmentById(@ApiParam(value = "space environment id", required = true) @PathParam("id") Long id) {
        EnvironmentDTO environmentDTO = null;
        try {
            if (id != null) {
                environmentDTO = environmentService.getEnvironment(id);
            }
            if (environmentDTO == null) {
                return Response.status(Response.Status.NOT_FOUND).entity("No saved environment was found").build();
            }

            if (!CSRestUtils.authorizedOnCS(environmentDTO.getSpaceGroupId())) {
                return Response.status(Response.Status.UNAUTHORIZED).entity("Your are not authorized").build();
            }
        } catch (Exception e) {
            LOG.error("Error while retrieving saved customer space environment", e);
            return Response.serverError().entity(e.getMessage()).build();
        }
        return Response.ok(EntityBuilder.fromEnvironmentDto(environmentDTO)).build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/settings")
    @RolesAllowed("users")
    @ApiOperation(
            value = "retrieves the customer space current user settings",
            httpMethod = "GET", response = Response.class, produces = "application/json"
    )
    @ApiResponses(
            value = {@ApiResponse(code = HTTPStatus.OK, message = "Request fulfilled"),
                    @ApiResponse(code = HTTPStatus.UNAUTHORIZED, message = "Unauthorized operation"),
                    @ApiResponse(code = HTTPStatus.INTERNAL_ERROR, message = "Internal server error"),}
    )
    public Response getCSUserSettings() {
        CSUserSettings csUserSettings = new CSUserSettings();
        try {
            User user = CSRestUtils.getCurrentUser();
            csUserSettings.setUserName(user.getUserName());
            csUserSettings.setFullName(user.getDisplayName());
            csUserSettings.setSupport(CSRestUtils.isSupportMember());
            csUserSettings.setCanManage(CSRestUtils.canManage());
            csUserSettings.setAvatarUrl(CSRestUtils.getProfile(user.getUserName()).getAvatarUrl());
        } catch (Exception e) {
            LOG.error("Error while getting customer space current user settings", e);
            return Response.serverError().entity(e.getMessage()).build();
        }
        return Response.ok(csUserSettings).build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{groupId}")
    @RolesAllowed("users")
    @ApiOperation(
            value = "retrieves the customer space information",
            httpMethod = "GET", response = Response.class, produces = "application/json"
    )
    @ApiResponses(
            value = {@ApiResponse(code = HTTPStatus.OK, message = "Request fulfilled"),
                    @ApiResponse(code = HTTPStatus.UNAUTHORIZED, message = "Unauthorized operation"),
                    @ApiResponse(code = HTTPStatus.INTERNAL_ERROR, message = "Internal server error"),}
    )
    public Response getSpaceByGroupId(@ApiParam(value = "space group id", required = true) @PathParam("groupId") String groupId) {
        SpaceDTO spaceDTO = null;
        if (groupId == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("space id is mandatory").build();
        }

        if (!CSRestUtils.authorizedOnCS(SPACE_GROUP + groupId)) {
            return Response.status(Response.Status.UNAUTHORIZED).entity("Your are not authorized").build();
        }

        try {
            spaceDTO = csSpaceService.getSpace(SPACE_GROUP + groupId);
        } catch (Exception e) {
            LOG.error("Error while getting customer space information", e);
            return Response.serverError().entity(e.getMessage()).build();
        }
        if (spaceDTO == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("ticket not found").build();
        }
        return Response.ok(CSRestUtils.extendCSSpace(EntityBuilder.fromSpaceDto(spaceDTO))).build();
    }

}
