package org.iri_research.renkan.models;

import java.util.UUID;

import org.iri_research.renkan.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@Document(collection = "edges")
@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class Edge extends AbstractRenkanModel<String> {

    @DBRef
    private Node from;

    @DBRef
    private Node to;

    @Field("project_id")
    @JsonProperty("project_id")
    private String projectId;

    @Field("created_by")
    @JsonProperty("created_by")
    private String createdBy;

    @SuppressWarnings("unused")
    private Edge() {
    }

    public Edge(Edge edge, Node from, Node to, String projectId) {
        this(Constants.UUID_GENERATOR.generate().toString(), edge.title,
                edge.description, edge.uri, edge.color, from, to,
                edge.createdBy, projectId);
    }

    public Edge(Edge edge) {
        this(edge, edge.from, edge.to, edge.projectId);
    }

    @Autowired(required = true)
    public Edge(String id, String title, String description, String uri,
            String color, Node from, Node to, String createdBy, String projectId) {
        super(id, title, description, uri, color);
        if(this.id == null) {
            this.id = Constants.UUID_GENERATOR.generate().toString();
        }
        this.from = from;
        this.to = to;
        this.createdBy = createdBy;
        this.projectId = projectId;
    }

    @JsonProperty("project_id")
    public String getProjectId() {
        return projectId;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    @JsonIgnore
    public Node getFromNode() {
        return this.from;
    }

    public String getFrom() {
        if (this.from != null) {
            return this.from.id;
        } else {
            return null;
        }
    }

    @JsonIgnore
    public Node getToNode() {
        return this.to;
    }

    public String getTo() {
        if (this.to != null) {
            return this.to.id;
        } else {
            return null;
        }
    }

    @Override
    protected String getRawKeyPart() {
        return this.createdBy;
    }

    @Override
    protected String getDefaultId() {
        return UUID.randomUUID().toString();
    }

}
