package sklep.photo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;

@Component
public class PhotoUtil {
	private static final String EXT = ".jpg";

	@Value("${alx.photo_dir}")
	private String dir;

	private Path getPath(int productId) {
		String fileName = productId + EXT;
		return Paths.get(dir, fileName);
	}

	public File getFile(int productId) {
		Path path = getPath(productId);
		File file = path.toFile();
		if(file.exists()) {
			return file;
		} else {
			throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Cannot read photo for product id = " + productId);
		}
	}

	public byte[] readBytes(int productId) {
		Path path = getPath(productId);
		try {
			return Files.readAllBytes(path);
		} catch(IOException e) {
			throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Cannot read photo for product id = " + productId);
		}
	}
}
