package com.eyrolles.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.eyrolles.model.Livre;
import com.eyrolles.service.ILivreService;


@RestController
@RequestMapping("/livre")
public class LivreController {
	@Autowired
	private ILivreService livreService;
	
	@RequestMapping("/{mc}")
	public Page<Livre> allByMC(@PathVariable String mc,@RequestParam int page,@RequestParam int size){
		return livreService.searchByMC(mc, page, size);
	}
	@RequestMapping("/theme/{idTheme}")
	public Page<Livre> allByTheme(@PathVariable int idTheme,@RequestParam int page,@RequestParam int size){
		return livreService.searchByTheme(idTheme, page, size);
	}
	@RequestMapping("/category/{idCategory}")
	public Page<Livre> allByCategory(@PathVariable int idCategory,@RequestParam int page,@RequestParam int size){
		return livreService.searchByCategory(idCategory, page, size);
	}
	@RequestMapping("/subCategory/{idSubCategory}")
	public Page<Livre> allBySubCategory(@PathVariable int idSubCategory,@RequestParam int page,@RequestParam int size){
		return livreService.searchBySubCategory(idSubCategory, page, size);
	}
	@RequestMapping(value="/photo/{id}",produces=MediaType.IMAGE_JPEG_VALUE)
	@ResponseBody
	public byte[] getPhoto(@PathVariable int id) throws IOException{
		Livre l=livreService.details(id);
		if(l.getPhoto()==null) 
			return new byte[0];
		else 
			return IOUtils.toByteArray(new ByteArrayInputStream(l.getPhoto()));
	}
	
}
