package org.codiki.categories;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.codiki.core.entities.dto.CategoryDTO;
import org.codiki.core.entities.persistence.Category;
import org.codiki.core.repositories.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {
	
	@Autowired
	private CategoryRepository categoryRepository;
	
	@GetMapping("/{id}")
	public CategoryDTO findById(@PathVariable("id") final Long pId) {
		final Optional<Category> result = categoryRepository.findById(pId);
		return result.isPresent() ? new CategoryDTO(result.get()) : null;
	}
	
	@GetMapping("/")
	public List<CategoryDTO> getAll() {
		return StreamSupport.stream(categoryRepository.findAll().spliterator(), false)
				.map(CategoryDTO::new).collect(Collectors.toList());
	}
}
