package com.eyrolles.service;

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

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

import com.eyrolles.model.Categorie;
import com.eyrolles.model.SousCategorie;
import com.eyrolles.model.Theme;
import com.eyrolles.repository.CategorieRepository;
import com.eyrolles.repository.SousCategorieRepository;
import com.eyrolles.repository.ThemeRepository;

@Service
public class ThemeService implements IThemeService {
	
	@Autowired
	ThemeRepository themeRepository;
	@Autowired
	CategorieRepository categorieRepository;
	@Autowired
	SousCategorieRepository sousCategorieRepository;
	
	public List<Theme> all(){
		List<Theme> themes=themeRepository.findAll();
		return themes;
	}
	public Theme add(Theme t){
		return themeRepository.save(t);
	}
	public Theme change(Theme t){
		return themeRepository.save(t);
	}
	public Theme details(int idTheme){
		Theme t=themeRepository.findOne(idTheme);
		return t;
	} 
	public Theme add(Theme t,Categorie c){
		categorieRepository.save(c);
		if (t.getCategories() == null)
			t.setCategories(new ArrayList<Categorie>());
		t.getCategories().add(c);
		return themeRepository.save(t);
	}
	public Theme change(Theme t,Categorie c){
		c.setTheme(t);
		for(Categorie e:t.getCategories())
			if(e.getId()==c.getId()){
				t.getCategories().remove(e);
				t.getCategories().add(c);
			}
		return themeRepository.save(t);
	}
	public Theme delete(Theme t,Categorie c){
		t.getCategories().remove(c);
		return themeRepository.save(t);
	}
	
	public Categorie add(Categorie c, SousCategorie sc){
		sousCategorieRepository.save(sc);
		if (c.getSousCategories() == null)
			c.setSousCategories(new ArrayList<SousCategorie>());
			c.getSousCategories().add(sc);
		c=categorieRepository.save(c);
		return c;
	}
	public Categorie change(Categorie c, SousCategorie sc){
		sc.setCategorie(c);
		for(SousCategorie scat:c.getSousCategories())
			if(scat.getId()==sc.getId()){
				c.getSousCategories().remove(scat);
				c.getSousCategories().add(sc);
			}
		return  categorieRepository.save(c);
	}
	public Categorie delete(Categorie c, SousCategorie sc){
		c.getSousCategories().remove(sc);
		return categorieRepository.save(c);
	}
}
