package sklep.rest;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.config.inject.ConfigProperty;

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

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

    @ConfigProperty(name="alx.photo_dir")
    private String dir;

    public File getFile(int productId) {
        Path path = getPath(productId);
        File file = path.toFile();
        if(file.exists()) {
            return file;
        } else {
            throw new WebApplicationException("Brak zdjęcia nr " + productId, Response.Status.NOT_FOUND);
        }
    }

    public byte[] readBytes(int productId) {
        Path path = getPath(productId);
        try {
            return Files.readAllBytes(path);
        } catch (IOException e) {
            throw new WebApplicationException("Brak zdjęcia nr " + productId, Response.Status.NOT_FOUND);
        }
    }

	public void writeStream(int productId, InputStream inputStream) {
		try {
			Path path = getPath(productId);
			Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
		} catch (Exception e) {
			// wypisujemy błąd, ale metoda kończy się normalnie
			e.printStackTrace();
		}
	}

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

    public void writeBytes(int productId, byte[] bytes) {
        try {
            Path path = getPath(productId);
            Files.write(path, bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
