package com.altamiracorp.lumify.web.routes.entity;

import com.altamiracorp.lumify.core.model.audit.AuditRepository;
import com.altamiracorp.lumify.core.model.graph.GraphRelationship;
import com.altamiracorp.lumify.core.model.graph.GraphRepository;
import com.altamiracorp.lumify.core.model.graph.GraphVertex;
import com.altamiracorp.lumify.core.model.ontology.LabelName;
import com.altamiracorp.lumify.core.model.ontology.PropertyName;
import com.altamiracorp.lumify.core.user.User;
import com.altamiracorp.lumify.web.BaseRequestHandler;
import com.altamiracorp.miniweb.HandlerChain;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class EntityObjectDetectionDelete extends BaseRequestHandler {
    private final GraphRepository graphRepository;
    private final EntityHelper entityHelper;
    private final AuditRepository auditRepository;

    @Inject
    public EntityObjectDetectionDelete(
            final GraphRepository graphRepository,
            final EntityHelper entityHelper,
            final AuditRepository auditRepository) {
        this.graphRepository = graphRepository;
        this.entityHelper = entityHelper;
        this.auditRepository = auditRepository;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception {
        JSONObject jsonObject = new JSONObject(getRequiredParameter(request, "objectInfo"));
System.out.println ("______________________________________________________________________");
System.out.println ("JSONOBJECT: " + jsonObject);
System.out.println ("______________________________________________________________________");
        User user = getUser(request);

        // Delete just the relationship if vertex has more than one relationship otherwise delete vertex
        String graphVertexId = jsonObject.getString("graphVertexId");
        JSONObject obj = new JSONObject();
        obj.put("entityVertex", graphRepository.findVertex(graphVertexId, user).toJson());
        Map<GraphRelationship, GraphVertex> relationships = graphRepository.getRelationships(graphVertexId, user);
        GraphVertex artifactVertex = graphRepository.findVertex(jsonObject.getString("artifactId"), user);
        if (relationships.size() > 1) {
            String edgeId = artifactVertex.getId() + ">" + graphVertexId + "|" + LabelName.CONTAINS_IMAGE_OF.toString();
            obj.put("edgeId", edgeId);
            graphRepository.removeRelationship(artifactVertex.getId(), graphVertexId, LabelName.CONTAINS_IMAGE_OF.toString(), user);
        } else {
            auditRepository.audit(artifactVertex.getId(), auditRepository.deleteEntityAuditMessage(artifactVertex.getProperty(PropertyName.TITLE.toString())), user);
//            auditRepository.audit(graphVertexId, auditRepository.deleteEntityAuditMessage());
            graphRepository.remove(graphVertexId, user);
            obj.put("remove", true);
        }

        // Delete the appropriate detected object json object from the array and reset the property
        JSONArray detectedObjects = new JSONArray(artifactVertex.getProperty(PropertyName.DETECTED_OBJECTS).toString());
        boolean deleted = false;
        for (int i = 0; i < detectedObjects.length(); i++) {
            JSONObject detectedObject = detectedObjects.getJSONObject(i);
            if (detectedObject.has("graphVertexId") && detectedObject.get("graphVertexId").equals(jsonObject.get("graphVertexId"))) {
                detectedObjects.remove(i);
                deleted = true;
            }
        }
        if (!deleted) {
            throw new RuntimeException("Tag was not found in the list of detected objects");
        }
        artifactVertex.setProperty(PropertyName.DETECTED_OBJECTS, detectedObjects.toString());
        graphRepository.save(artifactVertex, user);

        auditRepository.audit(artifactVertex.getId(), auditRepository.vertexPropertyAuditMessages(artifactVertex, Lists.newArrayList(PropertyName.DETECTED_OBJECTS.toString())), user);

        JSONObject updatedArtifactVertex = entityHelper.formatUpdatedArtifactVertexProperty(artifactVertex.getId(), PropertyName.DETECTED_OBJECTS.toString(), artifactVertex.getProperty(PropertyName.DETECTED_OBJECTS));
        obj.put("updatedArtifactVertex", updatedArtifactVertex);

        //TODO: Overwrite old ElasticSearch index with new info

        respondWithJson(response, obj);
    }
}

@@ -1618,248 +1618,8 @@
 ));%0A
-System.out.println (%22______________________________________________________________________%22);%0ASystem.out.println (%22JSONOBJECT: %22 + jsonObject);%0ASystem.out.println (%22______________________________________________________________________%22);%0A
     
@@ -2637,64 +2637,30 @@
 age(
-artifactVertex.getProperty(PropertyName.TITLE.toString()
+jsonObject.get(%22title%22
 )), 
@@ -2666,18 +2666,16 @@
  user);%0A
-//
         
@@ -2756,17 +2756,46 @@
 Message(
-)
+jsonObject.get(%22title%22)), user
 );%0A     

fix audit message for deletion