package com.sharefaith.thesharefaithapp;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.google.android.gms.analytics.Tracker;
import com.sharefaith.thesharefaithapp.base.NotificationUtils;
import com.sharefaith.thesharefaithapp.base.SFAppData;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFBackgroundSync;
import com.sharefaith.thesharefaithapp.base.SFConfig;
import com.sharefaith.thesharefaithapp.base.SFConstants;
import com.sharefaith.thesharefaithapp.base.SFPushHandler;
import com.sharefaith.thesharefaithapp.base.SFUtil;
import com.sharefaith.thesharefaithapp.ui.SFChurchChooserActivity;
import com.sharefaith.thesharefaithapp.ui.SFSharedUIMethods;

import java.io.File;

/**
 * Created by Anthony on 1/26/16.
 * MainActivity launched on startup sets up the application and starts the syncing process
 */
public class SFMainActivity extends Activity
{
	SFApplication mApplication = SFApplication.getInstance();
	SFConfig config = new SFConfig();
	String TAG = this.getClass().toString();

	//For Google Analytics tracking
	private Tracker mTracker;
	private NotificationUtils mNotificationUtils;

	@Override
	protected void onCreate( Bundle savedInstanceState )
	{

		super.onCreate( savedInstanceState );

		//if not tablet keep screen from rotating
		if( !SFConfig.isTablet() )
		{
			setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
		}
		this.requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView( R.layout.sf_splash_screen );
		getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		//this.mIinitialSyncProgressBar = (ProgressBar) findViewById( R.id.progressBar );

		//mApplication.setSfInitialSyncProgressBar( this.mIinitialSyncProgressBar );

		// Obtain the shared Tracker instance.
		mTracker = mApplication.getDefaultTracker();

		// If the app does not have a current church set, open the church chooser activity
		if(mApplication.getSfCurrentChurch().equals( "0" ))
		{
			Intent intent = new Intent( this, SFChurchChooserActivity.class );
			intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
			this.startActivity( intent );finish();
			this.overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
		}
		else
		{

			if (config.mLastSync < 1)
			{
				RelativeLayout footer = (RelativeLayout) findViewById( R.id.connecting_footer );
				footer.setVisibility( View.VISIBLE );
			}
			if (!mApplication.isSyncing && !mApplication.isAppRestarting)
			{
				//demoLinearLayout.setVisibility( View.INVISIBLE );
				mApplication.isSyncing = true;
				//this.showProgress( getString( R.string.connecting ), getString( R.string.getting_updates ) );

				Thread t = new Thread(
						new Runnable()
						{
							public void run()
							{
								SFBackgroundSync sync = new SFBackgroundSync( mApplication );
								sync.doSync();
							}
						}
				);
				t.start();


			}
			Thread t = new Thread(
					new Runnable()
					{
						public void run()
						{
							purgeOldBibleChapters();
						}
					}
			);
			t.start();

		}
		mNotificationUtils = new NotificationUtils(this);
	}

	/**
	 * purges old bible chapters from storage
	 */
	private void purgeOldBibleChapters()
	{
		SFAppData appData = new SFAppData();
		String[] chaptersToPurgeToPurge = appData.getChaptersToPurge();

		String biblePath = mApplication.getFilesDir() + "/appfiles/bibles/";
		File file;
		for( int i = 0; i < chaptersToPurgeToPurge.length; i++ )
		{
			file = new File( biblePath + chaptersToPurgeToPurge[i] );
			if(file.exists())
			{
				//Log.d("mTag", "deleting file: " + chaptersToPurgeToPurge[i]);
				file.delete();
			}
		}

	}

	@Override
	protected void onStart()
	{
		super.onStart();
		if( SFConstants.TRACK_ANALYTICS )
		{
			SFUtil.logSiteEvent( "Start Application" );
		}


	}

	@Override
	protected void onResume()
	{
		super.onResume();

		//Google Analytics tracking
		mApplication.logScreen( "main_screen" );
		mApplication.logEvent( "tracking", "trackuser", SFConstants.UAID_KEY );

		mApplication.setCurrentActivity( this );
		mApplication.currentViewTag = "main";
		mApplication.isInForground = true;
		this.mApplication.isNavOpen = false;

		// Handle an incoming push
		SFPushHandler push = new SFPushHandler( this ).getPush();
		//Log.d("mTag","mChannel = " + push.mChannel);
		if( push.mChannel > -1 && mApplication.mHavePush == false )
		{
			mApplication.mHavePush = true;
			//this.isSyncing = true;
			mApplication.handlePush( push );
		}

		if(config.mLastSync > 1)
		{
			//Log.d( "mTag","have push = " + mApplication.mHavePush );
			if(mApplication.mHavePush)
			{
				//Log.d("mTag", "*********** got push react to it *******");
				SFBackgroundSync sync = new SFBackgroundSync( mApplication );
				sync.updateInbox();
			}
			else
			{
				SFAppData appData = new SFAppData();
				String sectionTag = appData.getFirstSectionTag();
				mApplication.logEvent( "first_section",sectionTag );
				mApplication.currentSectionPosition = 0;
				//Log.d( "mTag","current section id = " + mApplication.currentSectionId );
				SFSharedUIMethods.swapToViewWithTag( sectionTag, 0 );finish();
			}
		}

	} // onResume()

	@Override
	public void onPause()
	{
		super.onPause();
		mApplication.isInForground = false;
	}

	@Override
	public void onLowMemory()
	{
		super.onLowMemory();
		mApplication.clearCaches();
	}

	/**
	 * View delegates and action handlers
	 */
	@Override
	public boolean onCreateOptionsMenu( Menu menu )
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate( R.menu.sfmain, menu );
		return true;
	}

	@Override
	public boolean onOptionsItemSelected( MenuItem item )
	{
		return super.onOptionsItemSelected( item );
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}

}
