package com.sharefaith.thesharefaithapp.base;


import android.os.AsyncTask;
import android.view.View;

import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.models.SFSermonModel;

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

import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton;

/**
 * Created by Chris Ostmo on 2014-12-11.
 */
public class SFProgressDownload
{
	SFApplication mApplication = SFApplication.getInstance();
	String mAddress;
	String mOutputPath;
	public String mLocalFilename;
	public CircularProgressButton mProgressButton;
	public String mDownloadType;
	public SFSermonModel mSermon;
	public boolean mHadError = false;
	//public SFSeriesListAdapter.SermonButtonClickListener mSeriesListClickListener;


	public SFProgressDownload()
	{

	}

	// TODO: 2/16/16 fix progress bar

	// 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();

		if( this.mDownloadType.equals( "sermonaudio" ) )
		{
			this.mOutputPath = config.mMediaAssetPath;
		}
		else
		{
			this.mOutputPath = config.mCustomAssetPath;
		}

		String extension = "";
		try
		{
			extension = address.substring( address.lastIndexOf( "." ) );
		}
		catch( Exception e )
		{
			e.printStackTrace();
			return "";
		}

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

		DownloadWithProgressTask task = new DownloadWithProgressTask( this.mOutputPath );
		task.mProgressButton = this.mProgressButton;
		task.mCaller = this;
		try
		{
			task.execute( this.mAddress );
		}
		catch( Exception e )
		{
			this.mHadError = true;
			String message = mApplication.getString( R.string.file_error ) + e.getLocalizedMessage();
			mApplication.makeToast( message );
		}

		return this.mLocalFilename;

	}

	public void finish()
	{
		if( this.mDownloadType.equals( "sermonaudio" ) )
		{
			if( !this.mHadError )
			{
				this.mSermon.mAudioLocation = this.mLocalFilename;
				this.mSermon.mAudioDownloadProgress = 100;
				this.mSermon.mAudioDownloadDate = (int) SFUtil.currentTimestamp();
				this.mSermon.saveMembers();
			}

			//if( this.mSeriesListClickListener != null )
			{
			//	this.mSeriesListClickListener.finish();
			}
		}
		else if( this.mDownloadType.equals( "sermonnotes" ) )
		{
			if( !this.mHadError )
			{
				SFConfig config = new SFConfig();
				this.mSermon.mNotesLocation = this.mLocalFilename;
				this.mSermon.mNotesDownloadDate = (int) SFUtil.currentTimestamp();
				this.mSermon.saveMembers();
				mApplication.showNotesFile( config.mCustomAssetPath + mApplication.getSfCurrentSermon().mNotesLocation );
			}

			//if( this.mSeriesListClickListener != null )
			{
				//this.mSeriesListClickListener.finish();
			}
		}
	}

	private class DownloadWithProgressTask extends AsyncTask<String, Integer, Long>
	{
		public SFProgressDownload mCaller;
		public String mOutputPath;
		public long mTotalSize;
		public long mReceivedSize;
		public CircularProgressButton mProgressButton;
		public SFApplication mApplication = SFApplication.getInstance();
		private SFConfig mConfig = new SFConfig();

		public DownloadWithProgressTask( String outputPath )
		{
			this.mOutputPath = outputPath;
		}

		@Override
		protected Long doInBackground( String... urls )
		{
			this.mReceivedSize = 0;
			this.mTotalSize = 0;

			HttpURLConnection connection = null;
			try
			{
				final URL url = new URL( urls[0] );
				connection = (HttpURLConnection) url.openConnection();
				connection.connect();

				this.mTotalSize = connection.getContentLength();

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

				byte data[] = new byte[256];
				int count;
				while( (count = in.read( data )) != -1 )
				{
					this.mReceivedSize += count;
					out.write( data, 0, count );
					int totalToShow =  (int) Math.ceil( (this.mReceivedSize * 1.00) / (this.mTotalSize * 1.00 ) * 100 );
					//this.mProgressBar.setProgress( totalToShow );
                    publishProgress(totalToShow);
				}

				if( out != null ) { out.close(); }
				if( in != null ) { in.close(); }
			}
			catch( Exception e )
			{
				this.mCaller.mHadError = true;
				String message = mApplication.getString( R.string.file_error ) + e.getLocalizedMessage();
				mApplication.makeToast( message );
			}
			finally
			{
				if( connection != null )
				{
					connection.disconnect();
				}
			}

			return this.mTotalSize;
		}


		@Override
		protected void onProgressUpdate( Integer... progress )
		{
			//this.mProgressButton.setStrokeColor( Color.parseColor( "#ff" + mConfig.mNavColor ) );
			this.mProgressButton.setBackgroundColor( 00000000 );
			//this.mProgressButton.setProgress(progress[0]);
		}


		// run the next piece of the chain
		@Override
		protected void onPostExecute( Long result )
		{
			mApplication.logEvent( "audio","download" );
			//this.mProgressButton.setStrokeColor( Color.parseColor( "#ff" + mConfig.mNavColor ) );
			this.mProgressButton.setBackgroundColor( 00000000 );
			this.mProgressButton.revertAnimation();
			this.mProgressButton.setVisibility( View.GONE );
			//this.mProgressButton.setProgress( 0 );
			this.mCaller.finish();
		}




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

}
