package lab12;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ImgDownloader {

	public static void main(String[] args) throws IOException {
		Document doc =  Jsoup.connect(args[0]).get(); 
		Elements elements = doc.select("img[src]");
		for (Element el: elements) {
			String imgUrl = el.attr("abs:src");
			System.out.println(imgUrl);
			new Thread(() -> downloadImg(imgUrl, args[1]));
			
		}

	}

	private static void downloadImg(String imgUrl, String pathDir) {
		
		URL url;
		try {
			url = new URL(imgUrl);
			String fileName =url.getPath();
			fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
			URLConnection connection = url.openConnection();
			
			try (InputStream is = connection.getInputStream() ){
				Path path = Paths.get(pathDir, fileName);
				try (OutputStream os = new FileOutputStream(path.toFile())) {
					byte[] buffer = new byte[2048];
					int len;
					while (-1 != (len = is.read(buffer))) {
						os.write(buffer, 0, len);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}