/**
 * URLDownload - Generic class to download a file from the Web & save to a specified file
 * Returns: true if file write was successful, otherwise false
 * Usage: URLDownload.fileDownload(absolute_URL_to_file, absolute_path_to_write_file);
 */
package com.phonegap.plugin.share;

import java.io.*;
import java.net.*;

public class URLDownload {

	final static int size = 1024;
	final static int connectionTimeoutInSeconds = 20;
	final static int readTimeoutInSeconds = 15;
	private static Boolean result = false;
	
	public static Boolean fileUrl(String fAddress, String localFileName, String destinationDir) {
		OutputStream outStream = null;
		URLConnection  uCon = null;
		result = false;

		InputStream is = null;
		try {
			URL Url;
			byte[] buf;
			int ByteRead, ByteWritten = 0;
			Url = new URL(fAddress);

			outStream = new BufferedOutputStream(new FileOutputStream(destinationDir));
			uCon = Url.openConnection();
			uCon.setConnectTimeout(connectionTimeoutInSeconds * 1000);
			uCon.setReadTimeout(readTimeoutInSeconds * 1000);
			
			is = uCon.getInputStream();
			buf = new byte[size];
			while ((ByteRead = is.read(buf)) != -1) {
				outStream.write(buf, 0, ByteRead);
				ByteWritten += ByteRead;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				is.close();
				outStream.close();
				result = true;
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	public static Boolean fileDownload(String fAddress, String destinationDir) {
 
		int slashIndex = fAddress.lastIndexOf('/');
		int periodIndex = fAddress.lastIndexOf('.');
		Boolean result = false;

		String fileName = fAddress.substring(slashIndex + 1);

		if (periodIndex >= 1 && slashIndex >= 0 
				&& slashIndex < fAddress.length() - 1) {
			result = fileUrl(fAddress, fileName, destinationDir);
		}
		return result;
	}
}
