package io.lumify.web.routes.vertex;

import com.altamiracorp.miniweb.HandlerChain;
import com.google.inject.Inject;
import io.lumify.core.config.Configuration;
import io.lumify.core.exception.LumifyException;
import io.lumify.core.model.user.UserRepository;
import io.lumify.core.model.workspace.WorkspaceRepository;
import io.lumify.core.user.User;
import io.lumify.core.util.JsonSerializer;
import io.lumify.web.BaseRequestHandler;
import org.json.JSONArray;
import org.json.JSONObject;
import org.securegraph.*;

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

public class VertexRelationships extends BaseRequestHandler {
    private final Graph graph;
    private final String artifactHasEntityIri;

    @Inject
    public VertexRelationships(
            final Graph graph,
            final UserRepository userRepository,
            final WorkspaceRepository workspaceRepository,
            final Configuration configuration) {
        super(userRepository, workspaceRepository, configuration);
        this.graph = graph;

        this.artifactHasEntityIri = this.getConfiguration().get(Configuration.ONTOLOGY_IRI_ARTIFACT_HAS_ENTITY);
        if (this.artifactHasEntityIri == null) {
            throw new LumifyException("Could not find configuration for " + Configuration.ONTOLOGY_IRI_ARTIFACT_HAS_ENTITY);
        }
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception {
        User user = getUser(request);
        Authorizations authorizations = getAuthorizations(request, user);
        String workspaceId = getActiveWorkspaceId(request);

        String graphVertexId = getAttributeString(request, "graphVertexId");
        long offset = getOptionalParameterLong(request, "offset", 0);
        long size = getOptionalParameterLong(request, "size", 25);
        String edgeLabel = getOptionalParameter(request, "edgeLabel");

        Vertex vertex = graph.getVertex(graphVertexId, authorizations);
        if (vertex == null) {
            respondWithNotFound(response);
            return;
        }

        Iterable<Edge> edges;
        if (edgeLabel == null) {
            edges = vertex.getEdges(Direction.BOTH, authorizations);
        } else {
            edges = vertex.getEdges(Direction.BOTH, edgeLabel, authorizations);
        }

        JSONObject json = new JSONObject();
        JSONArray relationshipsJson = new JSONArray();
        long referencesAdded = 0, skipped = 0, totalReferences = 0;
        for (Edge edge : edges) {
            Vertex otherVertex = edge.getOtherVertex(vertex.getId(), authorizations);
            if (otherVertex == null) { // user doesn't have access to other side of edge
                continue;
            }

            if (edge.getLabel().equals(this.artifactHasEntityIri)) {
                totalReferences++;
                if (referencesAdded >= size) continue;
                if (skipped < offset) {
                    skipped++;
                    continue;
                }

                referencesAdded++;
            }

            JSONObject relationshipJson = new JSONObject();
            relationshipJson.put("relationship", JsonSerializer.toJson(edge, workspaceId, authorizations));
            relationshipJson.put("vertex", JsonSerializer.toJson(otherVertex, workspaceId, authorizations));
            relationshipsJson.put(relationshipJson);
        }
        json.put("totalReferences", totalReferences);
        json.put("relationships", relationshipsJson);

        respondWithJson(response, json);
    }
}

@@ -2603,170 +2603,69 @@
     
-Vertex otherVertex = edge.getOtherVertex(vertex.getId(), authorizations);%0A            if (otherVertex == null) %7B // user doesn't have access to other side of edge
+totalReferences++;%0A            if (referencesAdded %3E= size) %7B
 %0A   
@@ -2722,57 +2722,24 @@
 if (
-edge.getLabel().equals(this.artifactHasEntityIri)
+skipped %3C offset
 ) %7B%0A
@@ -2750,39 +2750,31 @@
             
-totalReferences
+skipped
 ++;%0A        
@@ -2785,116 +2785,117 @@
     
-if (referencesAdded %3E= size) continue;%0A                if (skipped %3C offset) %7B%0A                    skipped++
+continue;%0A            %7D%0A%0A            Vertex otherVertex = edge.getOtherVertex(vertex.getId(), authorizations)
 ;%0A  
@@ -2908,78 +2908,109 @@
     
- 
-       continue;%0A                %7D%0A%0A                referencesAdded++
+if (otherVertex == null) %7B // user doesn't have access to other side of edge%0A                continue
 ;%0A  
@@ -3348,24 +3348,55 @@
 nshipJson);%0A
+            referencesAdded++;%0A
         %7D%0A  

fix paging of relationships