package me.kitt3120.viperbot.managers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class DownloadManager {
	
	File defaultFolder = new File(System.getenv("APPDATA"), ".ViperBot/Downloads");
	
	public DownloadManager() {
		if(!defaultFolder.exists()) defaultFolder.mkdirs();
	}
	
	public File download(boolean delete, String link) throws IOException{
		URL url = new URL(link);
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();
		File f = new File(defaultFolder, link);
		FileOutputStream out = new FileOutputStream(f);
		byte[] buffer = new byte[1024];
		int len;
		while((len = in.read(buffer)) > 0){
			out.write(buffer, 0, len);
		}
		in.close();
		out.close();
		if(delete) f.deleteOnExit();
		return f;
	}

	public File download(File folder, boolean delete, String link) throws IOException{
		URL url = new URL(link);
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();
		File f = new File(folder, link);
		FileOutputStream out = new FileOutputStream(f);
		byte[] buffer = new byte[1024];
		int len;
		while((len = in.read(buffer)) > 0){
			out.write(buffer, 0, len);
		}
		in.close();
		out.close();
		if(delete) f.deleteOnExit();
		return f;
	}
	
	public File download(File folder, String fileName, boolean delete, String link) throws IOException{
		URL url = new URL(link);
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();
		File f = new File(folder, fileName);
		FileOutputStream out = new FileOutputStream(f);
		byte[] buffer = new byte[1024];
		int len;
		while((len = in.read(buffer)) > 0){
			out.write(buffer, 0, len);
		}
		in.close();
		out.close();
		if(delete) f.deleteOnExit();
		return f;
	}

}