package io.lumify.web.routes.workspace;

import io.lumify.core.config.Configuration;
import io.lumify.core.model.user.UserRepository;
import io.lumify.core.model.workspace.Workspace;
import io.lumify.core.model.workspace.WorkspaceAccess;
import io.lumify.core.model.workspace.WorkspaceRepository;
import io.lumify.core.user.User;
import io.lumify.core.util.LumifyLogger;
import io.lumify.core.util.LumifyLoggerFactory;
import io.lumify.web.BaseRequestHandler;
import io.lumify.miniweb.HandlerChain;
import com.google.inject.Inject;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WorkspaceUpdate extends BaseRequestHandler {
    private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(WorkspaceUpdate.class);
    private final WorkspaceRepository workspaceRepository;

    @Inject
    public WorkspaceUpdate(
            final WorkspaceRepository workspaceRepository,
            final UserRepository userRepository,
            final Configuration configuration) {
        super(userRepository, workspaceRepository, configuration);
        this.workspaceRepository = workspaceRepository;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception {
        final String workspaceId = getAttributeString(request, "workspaceId");
        final String data = getRequiredParameter(request, "data");

        User authUser = getUser(request);

        Workspace workspace = workspaceRepository.findById(workspaceId, authUser);
        if (workspace == null) {
            respondWithNotFound(response);
            return;
        }

        JSONObject dataJson = new JSONObject(data);

        if (dataJson.has("title")) {
            setTitle(workspace, dataJson.getString("title"), authUser);
        }

        JSONArray entityUpdates = dataJson.getJSONArray("entityUpdates");
        updateEntities(workspace, entityUpdates, authUser);

        JSONArray entityDeletes = dataJson.getJSONArray("entityDeletes");
        deleteEntities(workspace, entityDeletes, authUser);

        JSONArray userUpdates = dataJson.getJSONArray("userUpdates");
        updateUsers(workspace, userUpdates, authUser);

        JSONArray userDeletes = dataJson.getJSONArray("userDeletes");
        deleteUsers(workspace, userDeletes, authUser);

        JSONObject resultJson = new JSONObject();
        resultJson.put("result", "OK");
        respondWithJson(response, resultJson);
    }

    private void setTitle(Workspace workspace, String title, User authUser) {
        LOGGER.debug("setting title (%s): %s", workspace.getWorkspaceId(), title);
        workspaceRepository.setTitle(workspace, title, authUser);
    }

    private void deleteUsers(Workspace workspace, JSONArray userDeletes, User authUser) {
        for (int i = 0; i < userDeletes.length(); i++) {
            String userId = userDeletes.getString(i);
            LOGGER.debug("user delete (%s): %s", workspace.getWorkspaceId(), userId);
            workspaceRepository.deleteUserFromWorkspace(workspace, userId, authUser);
        }
    }

    private void updateUsers(Workspace workspace, JSONArray userUpdates, User authUser) {
        for (int i = 0; i < userUpdates.length(); i++) {
            JSONObject update = userUpdates.getJSONObject(i);
            LOGGER.debug("user update (%s): %s", workspace.getWorkspaceId(), update.toString());
            String userId = update.getString("userId");
            WorkspaceAccess workspaceAccess = WorkspaceAccess.valueOf(update.getString("access"));
            workspaceRepository.updateUserOnWorkspace(workspace, userId, workspaceAccess, authUser);
        }
    }

    private void deleteEntities(Workspace workspace, JSONArray entityDeletes, User authUser) {
        for (int i = 0; i < entityDeletes.length(); i++) {
            String entityId = entityDeletes.getString(i);
            LOGGER.debug("workspace delete (%s): %s", workspace.getWorkspaceId(), entityId);
            workspaceRepository.softDeleteEntityFromWorkspace(workspace, entityId, authUser);
        }
    }

    private void updateEntities(Workspace workspace, JSONArray entityUpdates, User authUser) {
        for (int i = 0; i < entityUpdates.length(); i++) {
            JSONObject update = entityUpdates.getJSONObject(i);
            LOGGER.debug("workspace update (%s): %s", workspace.getWorkspaceId(), update.toString());
            String entityId = update.getString("vertexId");
            JSONObject graphPosition = update.optJSONObject("graphPosition");
            Integer graphPositionX = null;
            Integer graphPositionY = null;
            if (graphPosition != null)  {
                graphPositionX = graphPosition.getInt("x");
                graphPositionY = graphPosition.getInt("y");
            }
            workspaceRepository.updateEntityOnWorkspace(workspace, entityId, true, graphPositionX, graphPositionY, authUser);
        }
    }
}

@@ -34,16 +34,49 @@
 space;%0A%0A
+import com.google.inject.Inject;%0A
 import i
@@ -466,30 +466,28 @@
 ify.
+mini
 web.
-BaseRequest
 Handler
+Chain
 ;%0Aim
@@ -505,61 +505,30 @@
 ify.
-miniweb.HandlerChain;%0Aimport com.google.inject.Inject
+web.BaseRequestHandler
 ;%0Aim
@@ -1398,34 +1398,14 @@
 getA
-ttributeString(request, %22w
+ctiveW
 orks
@@ -1410,17 +1410,24 @@
 kspaceId
-%22
+(request
 );%0A     
@@ -4762,17 +4762,16 @@
 != null)
- 
  %7B%0A     

support workspaceId in the header