package com.sharefaith.thesharefaithapp.adapters;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Build;
import androidx.core.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFConfig;
import com.sharefaith.thesharefaithapp.base.SFConstants;
import com.sharefaith.thesharefaithapp.base.SFProgressDownload;
import com.sharefaith.thesharefaithapp.base.SFUtil;
import com.sharefaith.thesharefaithapp.models.SFSermonModel;
import com.sharefaith.thesharefaithapp.ui.SFDownloadsActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link android.app.Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 *
 */
public class SFDownloadsAdapter extends BaseAdapter
{
	public SFSermonModel[] mItems;
	public Context mContext;
	//public int mOpenRow;
	public SFApplication mApplication;
	public SFConfig mConfig;

	public String[] mButtonTitles;
	public String[] mButtonActions;
	public Button[] mButtons;

	/**
	 * Constructor
	 * @param context
	 * @param items
	 */
	public SFDownloadsAdapter( Context context, SFSermonModel[] items )
	{
		this.mItems = items;
		this.mContext = context;
		this.mApplication = SFApplication.getInstance();
		this.mConfig = new SFConfig();

		this.mButtonTitles = new String[3];
		this.mButtonTitles[0] = mApplication.getString( R.string.button_listen );
		this.mButtonTitles[1] = mApplication.getString( R.string.button_watch );
		this.mButtonTitles[2] = mApplication.getString( R.string.button_notes );

		this.mButtonActions = new String[3];
		this.mButtonActions[0] = "listen";
		this.mButtonActions[1] = "watch";
		this.mButtonActions[2] = "notes";
	}

	/**
	 *
	 * @param position
	 * @param convertView
	 * @param parent
	 * @return
	 */
	@Override
	public View getView(final int position, View convertView, ViewGroup parent )
	{
		View v = convertView;

		LayoutInflater vi = LayoutInflater.from( this.mContext );
		v = vi.inflate( R.layout.sf_downloads_item, null );  // Posts and Newsletters use the same interface


		v.setOnLongClickListener( new View.OnLongClickListener()
		{
			@Override
			public boolean onLongClick( View v )
			{
				if(mApplication.getNowPlayingSermon() == null || (!mItems[position].mTitle.equals( mApplication.getNowPlayingSermon().mTitle ) && position != 0 ) )
				{
					SFDownloadsActivity downloadsActivity = (SFDownloadsActivity) mApplication.getCurrentActivity();
					downloadsActivity.deleteSermonOverlay( position );
				}
				return true;
			}
		} );

		v.setOnClickListener( new View.OnClickListener()
		{
			@Override
			public void onClick( View v )
			{
				SFDownloadsActivity downloadsActivity = (SFDownloadsActivity) mApplication.getCurrentActivity();
				downloadsActivity.changeSermon( position );
			}
		} );

		SFSermonModel currentObject = this.mItems[position];
		if( currentObject != null )
		{
			TextView titleView = (TextView) v.findViewById( R.id.downloadedItemTextView );
			String showTitle = SFUtil.stripHtml( currentObject.mTitle ).toString();
			if( titleView != null )
			{
				int parentViewHeight = mApplication.getResources().getInteger( R.integer.sf_download_listitem_height_default );
				if( position == mApplication.OpenDownloadSermon )
				{
					parentViewHeight = mApplication.getResources().getInteger( R.integer.sf_download_listitem_height_open );
				}

				ListView.LayoutParams parentParams = new ListView.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, (int)SFUtil.dp2px( parentViewHeight ) );
				v.setLayoutParams( parentParams );

				// Now the child
				// move the title into the right position
				int textViewTopMargin = 10;
				int textViewBottomMargin = 10;

				RelativeLayout.LayoutParams marginParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, (int)SFUtil.dp2px( 26 ) );
				marginParams.addRule( RelativeLayout.RIGHT_OF, R.id.sermonPlayDate );
				if( position == mApplication.OpenDownloadSermon )
				{
					textViewTopMargin = 10;
					textViewBottomMargin = 50;
				}

				marginParams.setMargins(
						(int) SFUtil.dp2px( 15 ), (int) SFUtil.dp2px( textViewTopMargin ),
						(int) SFUtil.dp2px( 15 ), (int) SFUtil.dp2px( textViewBottomMargin )
				);
				titleView.setLayoutParams( marginParams );

				//titleView.setTypeface( SFTypeFaceSpan.getAssetTypeface( mContext.getResources().getString( R.string.font_regular ) ) );
				//titleView.setTextSize( mApplication.getResources().getDimension( R.dimen.sermon_title_list_font_size ) );
				titleView.setText( showTitle );
			} // if( titleView != null )

			this.mButtons = new Button[3];
			this.mButtons[0] = (Button) v.findViewById( R.id.downloadsListenButton );
			this.mButtons[1] = (Button) v.findViewById( R.id.downloadsWatchButton );
			this.mButtons[2] = (Button) v.findViewById( R.id.downloadsNotesButton );

			ProgressBar[] progressBars = new ProgressBar[3];

			for( int i = 0; i < this.mButtons.length; i++)
			{
				//this.mButtons[i].setTextSize( mApplication.getResources().getDimension( R.dimen.sf_small_button_label_font_size ) );
				this.mButtons[i].setTextColor( Color.parseColor( "#" + this.mConfig.customFontColorForNavColor() ) );
				this.mButtons[i].setText( this.mButtonTitles[ i ].toUpperCase() );
				int backgroundColor = Color.parseColor( "#ff" + mConfig.mNavColor );
				Drawable background = mApplication.getResources().getDrawable( R.drawable.borderbox_rounded_holo );
				background.setColorFilter( backgroundColor , PorterDuff.Mode.MULTIPLY );
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
				{
					this.mButtons[i].setBackground( background );
				}

				if( i == 2 )
				{
					progressBars[ i ] = (ProgressBar) v.findViewById( R.id.notesDownloadProgressBar );
					Resources res = this.mApplication.getResources();
					Rect bounds = progressBars[i].getProgressDrawable().getBounds();
					progressBars[i].setProgressDrawable( res.getDrawable( R.drawable.download_progress_drawable ) );
					progressBars[i].getProgressDrawable().setBounds( bounds );
					LayerDrawable progressDrawable = (LayerDrawable) progressBars[i].getProgressDrawable();
					if( progressDrawable != null )
					{
						progressDrawable.setColorFilter( Color.parseColor( "#" + this.mConfig.customFontColorForNavColor() ), PorterDuff.Mode.SRC_IN );
					}
				}
				else
				{
					progressBars[i] = null;
				}

				SermonButtonClickListener listener = new SermonButtonClickListener( this.mButtonActions[i], currentObject, this.mButtons[i], progressBars[i] );
				this.mButtons[i].setOnClickListener( listener );

			}
			this.setButtonState( currentObject, position , progressBars );

		} // if( currentObject != null )

		return v;
	}

	/**
	 * Sets the state of the buttons
	 * @param sermon
	 * @param position
	 * @param progressBars
	 */
	public void setButtonState(SFSermonModel sermon, int position, ProgressBar[] progressBars)
	{
		if( position != mApplication.OpenDownloadSermon )
		{
			for( int i = 0; i < this.mButtons.length; i++ )
			{
				this.mButtons[i].setVisibility( View.GONE );
			}
			return;
		}

		for( int i = 0; i < this.mButtons.length; i++ )
		{
			if( i == 0 )
			{
				/*TODO this function is only called on app start and it seems this section is never ever reached
				if (progressBars[0].getVisibility() == View.VISIBLE)
				{
					this.mButtons[i].setVisibility(View.GONE);
				} else {*/
					this.mButtons[i].setVisibility(View.VISIBLE);
				//}
				this.mButtons[ i ].setAlpha( (float) 1.0 );
			}
			else if( i == 1 )
			{
				if( sermon.mVideoUrl.length() > 0 )
				{
					this.mButtons[ i ].setVisibility( View.VISIBLE );
					this.mButtons[ i ].setAlpha( (float) 1.0 );
				}
				else
				{
					this.mButtons[ i ].setVisibility( View.INVISIBLE );
				}
			}
			else if( i == 2 )
			{
				if( sermon.mNotesLocation.length() > 0 || sermon.mNotesUrl.length() > 0 )
				{
					this.mButtons[ i ].setVisibility( View.VISIBLE );
					this.mButtons[ i ].setAlpha( (float) 1.0 );
				}
				else
				{
					this.mButtons[ i ].setVisibility( View.INVISIBLE );
				}
			}
		} // for( int i = 0; i < buttons.length; i++ )
	}

	/**
	 *  Actions to get number of items in arraylist
	 *
	 * @since		20120106
	 */

	@Override
	public int getCount()
	{
		return this.mItems.length;
	}

	/**
	 *  Actions to get position of item
	 *
	 * @since		20120106
	 */

	@Override
	public Object getItem( int position )
	{
		return null;
	}

	/**
	 *  Actions to get item ID
	 *
	 * @since		20120106
	 */

	@Override
	public long getItemId( int id )
	{
		return 0;
	}

	/**
	 * Listener for sermon buttons
	 */
	public class SermonButtonClickListener implements View.OnClickListener
	{
		String mAction;
		SFSermonModel mSermon;
		Button mButton;
		SFConfig mConfig;
		ProgressBar mProgressBar;
		SFProgressDownload mDownload;
		SFDownloadsAdapter mDownloadsAdapter;

		/**
		 * Create the listener for sermon buttons
		 * @param whichAction
		 * @param whichSermon
		 * @param whichButton
		 * @param whichProgressBar
		 */
		public SermonButtonClickListener( String whichAction, SFSermonModel whichSermon, Button whichButton, ProgressBar whichProgressBar )
		{
			this.mAction = whichAction;
			this.mSermon = whichSermon;
			this.mButton = whichButton;
			this.mConfig = new SFConfig();
			this.mProgressBar = whichProgressBar;
		}

		/**
		 * @deprecated
		 * @param whichAction
		 * @param whichSermon
		 * @param whichButton
		 * @param whichProgressBar
		 * @param downloadsAdapter
		 */
		public SermonButtonClickListener( String whichAction, SFSermonModel whichSermon, Button whichButton, ProgressBar whichProgressBar, SFDownloadsAdapter downloadsAdapter )
		{
			this( whichAction, whichSermon, whichButton, whichProgressBar );
			this.mDownloadsAdapter = downloadsAdapter;
		}

		/**
		 * @deprecated
		 */
		public SermonButtonClickListener()
		{

		}

		/**
		 *
		 * @param v
		 */
		@Override
		public void onClick( View v )
		{
			//Log.d("mTag","SermonButtonClick Triggered");
			if( this.mAction.equals( "listen" ) )
			{
				mApplication.logEvent( "playlist_action","play" );
				SFUtil.logSiteEvent( "listen audio" );

				if( this.mSermon != mApplication.getSfCurrentSermon() )
				{
					mApplication.setSfCurrentSermon( this.mSermon );
					SFDownloadsActivity downloadsActivity = (SFDownloadsActivity) mApplication.getCurrentActivity();
					downloadsActivity.notifySermonChange();
					downloadsActivity.playOnListen( this.mSermon );
				}

			}
			else if( this.mAction.equals( "watch" ) )
			{
				mApplication.logEvent( "playlist_action","watch" );
				SFUtil.logSiteEvent( "Watch sermon" );

				//Google Analytics tracking
				mApplication.logScreen("watch");
				mApplication.launchVideo( this.mSermon.mVideoUrl );
			}
			else if( this.mAction.equals( "notes" ) )
			{
				SFUtil.logSiteEvent( "Sermon notes" );

				//Google Analytics tracking
				mApplication.logEvent( "playlist_action","notes" );
				mApplication.logScreen("notes");
				if( this.mSermon.mNotesLocation.length() < 1 )
				{
					this.mDownload = new SFProgressDownload();

					//this.mDownload.mProgressBar = this.mProgressBar;
					this.mDownload.mDownloadType = "sermonnotes";
					this.mDownload.mSermon = this.mSermon;
					//this.mDownload.mSeriesListClickListener = this;

					try
					{
						this.mDownload.downloadFile( this.mSermon.mNotesUrl );
					} catch (Exception e)
					{
						this.mDownload.mHadError = true;
						String message = mApplication.getString( R.string.network_error ) + e.getLocalizedMessage();
						mApplication.makeToast( message );
					}
				}
				else
				{
					mApplication.showNotesFile( mConfig.mCustomAssetPath + this.mSermon.mNotesLocation );
				}
			}
		}

		/**
		 * @deprecated
		 * open notes file
		 * @param filePath
		 */
		public void showNotesFile( String filePath )
		{
			try
			{
				String mimeType = mApplication.getMimeType( filePath );
				if( mimeType == null )
				{
					mimeType = "";
				}


				// Grant permissions to registered apps
				final PackageManager pm = mApplication.getPackageManager();

				final IntentFilter filter = new IntentFilter( Intent.ACTION_MAIN );
				filter.addCategory( Intent.CATEGORY_LAUNCHER );

				List<IntentFilter> outFilters = new ArrayList<IntentFilter>();
				outFilters.add( filter );

				List<ComponentName> outActivities = new ArrayList<ComponentName>();
				pm.getPreferredActivities( outFilters, outActivities, null );

				File incomingFile = new File( filePath );
				Uri uri = FileProvider.getUriForFile( mApplication, SFConstants.CONTENT_PROVIDER, incomingFile );

				List<ResolveInfo> list = pm.queryIntentActivities( new Intent( Intent.ACTION_VIEW ), 0 );

				for( ResolveInfo resolveInfo : list )
				{
					String packageName = resolveInfo.activityInfo.packageName;
					mApplication.grantUriPermission( packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION );
				}

				Intent intentUrl = new Intent( Intent.ACTION_VIEW );
				intentUrl.setDataAndType( uri, mimeType );
				mApplication.getCurrentActivity().startActivity( intentUrl );

			}
			catch ( ActivityNotFoundException e )
			{
				String extension = MimeTypeMap.getFileExtensionFromUrl( filePath );
				String message = mApplication.getString( R.string.no_viewer_preamble ) + " " + extension.toUpperCase() + " " +  mApplication.getString( R.string.no_viewer_postamble );
				mApplication.makeToast( message );
			}
		}

		// action for completion of download

		public void finish()
		{
			if( this.mAction.equals( "download" ) )
			{
				this.mProgressBar.setVisibility( View.INVISIBLE );
				this.mButton.setText( mApplication.getString( R.string.button_download ).toUpperCase() );
				this.mButton.setVisibility( View.INVISIBLE );
				//this.mButton.setVisibility( View.VISIBLE );
				//this.mButton.setAlpha( (float) 0.2 ); Not working well
				this.mSermon.refreshMembers();
				//mApplication.reloadDownloadsScreen();
			}
			if( this.mAction.equals( "notes" ) )
			{
				this.mProgressBar.setVisibility( View.INVISIBLE );
				this.mButton.setText( mApplication.getString( R.string.button_notes ).toUpperCase() );
				this.mButton.setVisibility( View.VISIBLE );
				this.mButton.setAlpha( (float) 1.0 );
				this.mSermon.refreshMembers();
				this.mButton.setOnClickListener( new SermonButtonClickListener( "notes", this.mSermon, this.mButton, null ) );
				this.showNotesFile( this.mConfig.mCustomAssetPath + this.mSermon.mNotesLocation );
			}
		}
	}
}
