package KbExamples;

import com.aspose.slides.ApiException;
import com.aspose.slides.api.SlidesApi;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class Example_ReplacePictureInPresentation {
    protected static SlidesApi presentationApi;

    public Example_ReplacePictureInPresentation() {
        if (presentationApi == null) {
            presentationApi = new SlidesApi("appSid", "appKey");
        }
    }

    public void addPictureInSlide() throws ApiException, IOException {
        String localPath = "/home/downloads/";
        String fileName = "Sample.pptx";
        String outputFileName = "output.pptx";
        String replacedImageFileName = "ShapeImage.png";
        String storageFolderName = "TempTests";

        // Replace the image on the first slide
        presentationApi.replaceImage("InputSlides.pptx", 1,  readFileToByteArray(localPath + replacedImageFileName),
                null, null, storageFolderName);
        System.out.println("Image on index 1 has been replaced successfully.");

        File outputPresentationFile = presentationApi.downloadFile(storageFolderName+"/"+fileName, null, null);

        // Copy the downloaded presentation with new image shape to the local directory
        copyFile(outputPresentationFile, new File(localPath, outputFileName));

        System.out.println("Presentation slide with replaced image shape is copied to: " + localPath + fileName);
    }

    public static byte[] readFileToByteArray(String filePath) throws IOException {
        Path path = new File(filePath).toPath();
        return Files.readAllBytes(path);
    }

    private void copyFile(File sourceFile, File targetFile) throws IOException {
        if (sourceFile == null || !sourceFile.exists()) {
            throw new IOException("Source file does not exist: " + sourceFile);
        }

        // Ensure the target directory exists
        Path targetPath = targetFile.toPath();
        Files.createDirectories(targetPath.getParent());

        // Copy the file
        Files.copy(sourceFile.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
    }
}