package de.stoermer.redditdownloader;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

public class ImageDownloader {

	private final HttpClient httpClient;
	private String path;
	
	public ImageDownloader(String subreddit) {
		this.httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL).build();
		this.path = System.getProperty("user.home") + "/Downloads/reddit/" + subreddit + "/";
		new File(path).mkdirs();
	}

	public void downloadImage(String imageUrl, String destinationPath, String destinationFile) {
		try {
			File file = new File(path + destinationPath + "/" + destinationFile);
			if (!file.exists()) {				
				HttpRequest request = HttpRequest.newBuilder().uri(URI.create(imageUrl))
						.header("User-Agent", "Mozilla/5.0 (RedditDownloader/0.1)").GET().build();
				
				System.out.println("Downloade: " + imageUrl);
				
				new File(path + destinationPath).mkdirs(); 
				
				HttpResponse<Path> response = httpClient.send(request,
						HttpResponse.BodyHandlers.ofFile(file.toPath()));
				
				if (response.statusCode() != 200) {
					System.err.println("Fehler beim Download! HTTP Status: " + response.statusCode());
				}
			} else {
				System.out.println("Datei existiert bereit: " + file.getAbsolutePath());
			}
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
			Thread.currentThread().interrupt(); // Best Practice bei InterruptedException
		}
	}
}