package es.uv.saic.service;


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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import es.uv.saic.domain.Proces;
import es.uv.saic.domain.ProcesRepository;
import es.uv.saic.domain.Usuari;
import es.uv.saic.domain.UsuarisRol;

@Service
public class ProcesService {

	@Autowired
	private ProcesRepository procesRepository;
	
	@Autowired
	private UsuarisRolService urs;

	public Proces findByID(Integer id) {
		Optional<Proces> p = this.procesRepository.findById(id);
		if(p.isPresent()) {
			return p.get();
		}
		return null;
	}
	
	public List<Proces> findByName(String n) {
		return this.procesRepository.findByName(n);
	}
	
	public List<Proces> findByNameCurs(String n, Integer c) {
		return this.procesRepository.findByNameCurs(n, c);
	}
	
	public List<Proces> getAll(){
		return this.procesRepository.findAll();
	} 
	
	public List<Integer> getSupervisableCursos(List<Integer> centres, List<Integer> titulacions){
		return this.procesRepository.findCursosByCentreTitulacio(centres, titulacions);
	}
	
	public List<Integer> getSupervisableProcedures(Usuari usuari, List<Integer> cursos, List<Integer> centres, List<Integer> titulacions){
		
		List<String> a = new ArrayList<String>();
		for(UsuarisRol urol : urs.findActiveRols(usuari)) {
			if(this.urs.hasAssociatedProcs(urol.getRol().getNomRol())) { // rols especials
				a = this.urs.findAssociatedProcs(urol.getRol().getNomRol());
			}
		}
		
		if(a.size() == 0) {
			List<Integer> p_list = this.procesRepository.findProcsByCentreTitulacioCurs(cursos, centres, titulacions);
			if(p_list != null) {
				return p_list;
			}
		}
		else {
			List<Integer> p_list = new ArrayList<Integer>();
			for(String n : a) {
				List<Integer> ps = this.procesRepository.findProcsByCentreTitulacioCursNom(cursos, centres, titulacions, n);
				p_list.addAll(ps);
			}
			return p_list;
		}
		
		return new ArrayList<Integer>();
		
	}
	
	public void save(Proces p) {
		this.procesRepository.save(p);
		this.procesRepository.flush();
	}
	
	public void deleteById(Integer idProces) {
		this.procesRepository.deleteById(idProces);
	}
	
	public void delete(Proces proces) {
		this.procesRepository.delete(proces);
	}

	public List<String> getFlowDiagram(Proces proces){
		return this.procesRepository.getFlowDiagram(proces.getNomProces());
	}
	
}
