package org.codiki.categories;

import com.fasterxml.jackson.annotation.JsonView;
import org.codiki.core.entities.dto.View;
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;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {
	private final CategoryRepository categoryRepository;

	/** Constructor. */
	public CategoryController(CategoryRepository categoryRepository) {
		this.categoryRepository = categoryRepository;
	}

	@JsonView(View.CategoryDTO.class)
	@GetMapping("/{id}")
	public Category findById(@PathVariable("id") final Long pId,
							 HttpServletResponse response) {
		return categoryRepository.findByIdWithSubCategories(pId)
				.orElseGet(() -> {
					response.setStatus(HttpServletResponse.SC_NOT_FOUND);
					return null;
				});
	}

	@JsonView(View.CategoryDTO.class)
	@GetMapping("/")
	public List<Category> getAll() {
		return categoryRepository.findAllWithSubCategories();
	}
}
