package com.sharefaith.thesharefaithapp.base;

import android.os.AsyncTask;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Sharefaith1 on 2014-12-02.
 */
public class SFCustomDownload
{
	String mAddress;
	String mOutputPath;
	String mLocalFilename;
	boolean mDownloadFinished;
	boolean mhadError = false;
	public SFBackgroundSync mBackgroundSync;

	public SFCustomDownload()
	{
		this.mBackgroundSync = null;
	}

	public SFCustomDownload( SFBackgroundSync sync )
	{
		this();
		this.mBackgroundSync = sync;
	}

	// get the chain of events under way
	public String downloadFile( String address ) throws IOException
	{
		if( address.length() < 1 )
		{
			return "";
		}

		this.mAddress = address;

		SFConfig config = new SFConfig();

		this.mOutputPath = config.mCustomAssetPath;
		String extension = "";
		try
		{
			extension = address.substring( address.lastIndexOf( "." ) );
		}
		catch( Exception e )
		{
			return "";
		}

		extension = extension.substring( 1 );
		this.mLocalFilename = SFUtil.md5( address + SFUtil.currentTimestamp() + extension ) + "." + extension;
		this.mOutputPath = this.mOutputPath + this.mLocalFilename;

		this.mDownloadFinished = false;

		boolean didCopy = false;

		// detect if we already have the file, move it and return it if we do. Otherwise, download it
		String remoteFileName = this.mAddress.substring( this.mAddress.lastIndexOf( '/' ) + 1 );
		String localFilePath = config.mCustomAssetPath + "inapp/" + remoteFileName;
		File file = new File( localFilePath );
		if( file.exists() )
		{
			didCopy = file.renameTo( new File( this.mOutputPath ) );

			if( didCopy )
			{
				return this.mLocalFilename;
			}
		}
		// If we're here, either the file is not local, or the copy failed. Need to download it

		DownloadCustomTask task = new DownloadCustomTask( this );
		try
		{
			task.execute( this.mAddress );
		}
		catch( Exception e )
		{
			this.mDownloadFinished = true;
			this.mhadError = true;
			//String message = SFMainActivity.instance.getString( R.string.file_error ) + e.getLocalizedMessage();
			//SFMainActivity.makeToast( message );
		}

		// We need to loop until the downloader informs us that it's finished
		while( !this.mDownloadFinished )
		{
			try
			{
				Thread.sleep( 200 );
			}
			catch( InterruptedException e)
			{
				this.mhadError = true;
				this.mDownloadFinished = true;
				//String message = SFMainActivity.instance.getString( R.string.file_error ) + e.getLocalizedMessage();
				//SFMainActivity.makeToast( message );
			}
		}

		return this.mLocalFilename;

	}

	private class DownloadCustomTask extends AsyncTask<String, Integer, Long>
	{
		public SFCustomDownload mCaller;
		public String mOutputPath;
		public String mAddress;

		public DownloadCustomTask( SFCustomDownload caller )
		{
			this.mCaller = caller;
			this.mOutputPath = this.mCaller.mOutputPath;
			this.mAddress = this.mCaller.mAddress;
		}

		protected Long doInBackground( String... urls )
		{
			HttpURLConnection connection = null;
			try
			{
				final URL url = new URL( urls[0] );
				connection = (HttpURLConnection) url.openConnection();

				BufferedInputStream in = new BufferedInputStream( connection.getInputStream() );
				FileOutputStream out = new FileOutputStream( this.mOutputPath );

				// This is much faster
				byte data[] = new byte[256];
				int count;
				while( (count = in.read( data )) != -1 )
				{
					out.write( data, 0, count );

					if( this.mCaller.mBackgroundSync != null && this.mCaller.mBackgroundSync.mIsInitialSync )
					{
						this.mCaller.mBackgroundSync.updateProgress( count );
					}
				}


				if( out != null ) { out.close(); }
				if( in != null ) { in.close(); }

				this.mCaller.mDownloadFinished = true;
			}
			catch( Exception e )
			{
				this.mCaller.mDownloadFinished = true;
				this.mCaller.mhadError = true;
				//String message = SFMainActivity.instance.getString( R.string.file_error ) + e.getLocalizedMessage();
				//SFMainActivity.makeToast( message );
			}
			finally
			{
				if( connection != null )
				{
					connection.disconnect();
				}
			}

			long totalSize = 0;

			return totalSize;
		}

		// run the next piece of the chain
		protected void onPostExecute( Long result )
		{
			this.mCaller.mDownloadFinished = true;
		}




	} // private class DownloadTask extends AsyncTask<URL, Integer, Long>
}
