package ua.be.wee.controller.rest;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import ua.be.wee.model.pm.PM;
import ua.be.wee.model.repository.FusekiWrapper;
import ua.be.wee.model.repository.NodeRespository;
import ua.be.wee.model.repository.PMRepository;

@RestController
public class PMController {

	@Autowired
	private PMRepository pmRepo;
	
	@Autowired
	private NodeRespository nodesRepo;
	
	@Autowired
	public PMController(@Value("${endpoint}")final String endpoint) throws Exception {
		if (FusekiWrapper.getInstance().getServiceURI() == null) {
			FusekiWrapper.getInstance().setServiceURI(endpoint);
		}
	} 

	@CrossOrigin
	@GetMapping("/pms")
	public List<PM> all() throws Exception {
		List<PM> allPMs = pmRepo.getAllPMs();
		for (PM pm : allPMs) {
			pm.setNodes(nodesRepo.getNodes(pm.getIri()));
		}
		return allPMs;
	}
	
	@CrossOrigin
	@GetMapping("/pmss/{id}")
	public PM getPM(@PathVariable String id) throws Exception {
		PM pm = pmRepo.getPM(id);
		pm.setNodes(nodesRepo.getNodes(pm.getIri()));
		return pm;
	}
	
	@CrossOrigin
	@PutMapping("/endpoint")
	public boolean setEndpoint(@RequestBody String url) throws Exception {
		FusekiWrapper.getInstance().setServiceURI(url);
		return FusekiWrapper.getInstance().testEndpoint();
	}
		

}
