package org.iri_research.renkan.management;

import java.util.ArrayList;
import java.util.List;

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.NodesRepository;
import org.iri_research.renkan.repositories.ProjectsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.stereotype.Component;

@Component
public class CorrectProjectId implements CommandMarker {

//    public static void main(String[] args) {

//        @SuppressWarnings("resource")
//        ApplicationContext context = new ClassPathXmlApplicationContext(
//                "classpath:META-INF/applicationContext.xml");

//        CorrectProjectId p = context.getBean(CorrectProjectId.class);
//        p.start(args);

//    }

    @Autowired
    private ProjectsRepository projectsRepository;
    @Autowired
    private NodesRepository nodesRepository;
    @Autowired
    private EdgesRepository edgesRepository;
    
    @CliAvailabilityIndicator({"correct-project-id"})
    public boolean isCommandAvailable() {
        return true;
    }

    @CliCommand(value="correct-project-id", help="correct-project-id")
    public void start() {

        for (Project proj : projectsRepository.findAll()) {
            
            System.out.format("Processing project %s %n", proj.getId());

            if(proj.getNodes() != null) {
                List<Node> nodes = new ArrayList<>();
                for(Node node: proj.getNodes()) {
                    if(node != null && node.getProjectId() == null) {
                        node.setProjectId(proj.getId());
                        nodes.add(node);
                    }
                }
                nodesRepository.save(nodes);
            }
            System.out.format("Node saved %s %n", proj.getId());

            if(proj.getEdges() != null) {
                List<Edge> edges = new ArrayList<>();
                for(Edge edge : proj.getEdges()) {
                    if(edge != null && edge.getProjectId() == null) {
                        edge.setProjectId(proj.getId());
                        edges.add(edge);
                    }
                }
                edgesRepository.save(edges);
            }
            System.out.format("Edge saved %s %n", proj.getId());
        }
    }
}
