package org.iri_research.renkan.rest;

import java.util.Arrays;
import java.util.List;

import javax.inject.Singleton;
import javax.ws.rs.Path;

import org.iri_research.renkan.Constants;
import org.iri_research.renkan.models.Edge;
import org.iri_research.renkan.models.Node;
import org.iri_research.renkan.models.Project;
import org.iri_research.renkan.repositories.EdgesRepository;
import org.iri_research.renkan.repositories.IRenkanRepository;
import org.iri_research.renkan.repositories.NodesRepository;
import org.iri_research.renkan.repositories.ProjectsRepository;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//TODO: Add views management
//TODO: Add user management (on POST for example)
@Singleton
@Path("projects")
@Component
public class ProjectsResource extends RenkanResource<Project, String> {

    private Logger logger = LoggerFactory.getLogger(ProjectsResource.class);

    @Autowired
    private ProjectsRepository projectsRepository;
    @Autowired
    private NodesRepository nodesRepository;
    @Autowired
    private EdgesRepository edgesRepository;

    @Override
    protected IRenkanRepository<Project, String> getRepository() {
        return this.projectsRepository;
    }

    @Override
    protected String getNewId() {
        return Constants.UUID_GENERATOR.generate().toString();
    }

    @Override
    protected void prepareObject(Project obj) {
        if (obj.getCreated() == null) {
            obj.setCreated(new DateTime());
        }
        obj.setUpdated(new DateTime());
        
        for (Node node : obj.getNodes()) {
            node.setProjectId(obj.getId());
        }
        for (Edge edge : obj.getEdges()) {
            edge.setProjectId(obj.getId());
        }
    }

    @Override
    protected List<String> getObjectListFieldList() {
        return Arrays.asList(this.baseObjectListFieldList);
    }

    @Override
    protected void doDeleteObject(String objectId) {
        this.projectsRepository.deleteRecursive(objectId);
    }
    
    @Override
    protected Project saveObjectPost(Project obj) {
        
        logger.debug("Project Resource : Save object post " + obj.getTitle());
        this.nodesRepository.save(obj.getNodes());
        this.edgesRepository.save(obj.getEdges());
        return super.saveObjectPost(obj);
    }

}
