package com.sharefaith.thesharefaithapp.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;

import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.SFMainActivity;
import com.sharefaith.thesharefaithapp.base.SFAppData;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFConfig;
import com.sharefaith.thesharefaithapp.base.SFUtil;

import java.io.File;

public class SFSettingsActivity extends Activity {

    //Default classes to get access to shared resources.
    private SFApplication mApplication;
    private SFAppData mAppData;
    private SFConfig mConfig;

    //My designed screen controls.
    private Button mChangeMyChurch;
    private Button mResetAppData;
    private Button mClose;
    private ImageView mDefaultIcon;
    private ImageView mMyMinistryIcon;
    private Button mPrivacyBtn;

    //For displaying the menu when you swipe in the screen.
    private GestureDetector mDetector;
    private View.OnTouchListener mGestureListener;

    //Logging tag
    private String logTag = "Settings_Screen";

    public final String PRIVACY_POLICY_URL = "https://www.sharefaith.com/faith/privacyPolicy/view.do";


    @Override
    //Happens only once you hit this screen and will not be ran again until app restarts.
    protected void onCreate(Bundle savedInstanceState) {
        //Calls "oncreate" method that are created automatically, is the base class.
        super.onCreate(savedInstanceState);

        //Disable android default android title.
        this.requestWindowFeature( Window.FEATURE_NO_TITLE );

        //Sets the layout(design view) to the activity class.
        setContentView(R.layout.sf_settings);

        //if not tablet keep screen from rotating
        if( !SFConfig.isTablet() )
        {
            //Stay vertical/portrait.
            setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
        }

        //Creates an instance for the startup class.
        mApplication = SFApplication.getInstance();

        //Instantiating a class for doing any database activity.
        mAppData = new SFAppData();

        //gesture detection, for sliding to show menu.
        mDetector = new GestureDetector( this, new SFGestureListener() );

        //Setting a touch listener on view.
        mGestureListener = new View.OnTouchListener()
        {
            //Checking if a touch event is a motion event.
            public boolean onTouch( View v, MotionEvent event )
            {
                //Returns a touch event that was instantiated earlier causing the menu to show or hide.
                return mDetector.onTouchEvent( event );
            }
        };

        //For Flurry (Tracking).
        SFUtil.logSiteEvent( "Opened Settings" );
    }

    @Override
    //Happens every time you go back to this screen.
    protected void onResume()
    {
        //Runs base class first for "on resume".
        super.onResume();

        //Google Analytics Tracking.
        mApplication.logScreen("settings");

        //Sets the current activity as a reference.
        mApplication.setCurrentActivity( this );

        //Used to set the tag to know what view you are on.
        mApplication.currentViewTag = "settings";

        //Hotfix will prevent issues with reset app data in case the view is not longer there.
        if(mApplication.currentSettingsPosition == -2)
        {
            this.finish();
            return;
        }

        //Sets the current position.
        mApplication.currentSectionPosition = mApplication.currentSettingsPosition;

        //Create an instance to app configuration class (static variables).
        mConfig = new SFConfig();

        //Assigning buttons to class variables. TIP R is auto generated reference to design view control.
        mChangeMyChurch = (Button) findViewById(R.id.btnChangeMyChurch);
        mResetAppData = (Button) findViewById(R.id.btnResetAppData);
        mClose = (Button) findViewById(R.id.btnClose);
        mDefaultIcon = findViewById(R.id.ibtnDefaultIcon);
        mMyMinistryIcon = findViewById(R.id.ibtnMyMinistryIcon);
        mMyMinistryIcon.setImageResource( getResources().getIdentifier( "sf" + mApplication.getSfCurrentChurch(), "drawable", getPackageName() ) );
        mPrivacyBtn = (Button) findViewById(R.id.btnPrivacy);

        //Setup the methods to be called during an action with the controls;
        mChangeMyChurch.setOnClickListener( settingsControlsListener( "change_my_church" ) );
        mResetAppData.setOnClickListener( settingsControlsListener( "reset_my_app_data" ) );
        mClose.setOnClickListener( settingsControlsListener( "close" ) );
        mDefaultIcon.setOnClickListener( settingsControlsListener( "switch_icon_to_default" ) );
        mMyMinistryIcon.setOnClickListener( settingsControlsListener( "switch_icon_to_my_ministry" ) );
        mPrivacyBtn.setOnClickListener( settingsControlsListener("privacyPolicy"));
    }

    private View.OnClickListener settingsControlsListener( final String action )
    {
        return new View.OnClickListener()
        {
            public void onClick( View v )
            {
                switch(action){
                    case "change_my_church":
                        changeMyChurch();
                        break;

                    case "reset_my_app_data":
                        resetMyAppData();
                        break;

                    case "close":
                        closeSettingsScreen();
                        break;

                    case "switch_icon_to_default":
                        mApplication.setAppIcon("default");
                        //switchIconToDefault();
                        break;

                    case "switch_icon_to_my_ministry":
                        mApplication.setAppIcon(mApplication.getSfCurrentChurch());
                        //switchIconToMyMinistry();
                        break;
                    case "privacyPolicy":
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(PRIVACY_POLICY_URL));
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivity(intent);
                        }
                        break;

                    default:
                        Log.e(logTag, "You have assigned a action that does not exist! Doing nothing now! Action passed to be called = {" + action + "}");
                        break;
                }
            }
        };
    }

    private void changeMyChurch()
    {
        SFSharedUIMethods.closeMenu();
        Intent intent = new Intent( mApplication, SFChurchChooserActivity.class );
        startActivity( intent );
        overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
    }

    private void resetMyAppData()
    {
        SFAppData data = new SFAppData();
        SFConfig config = new SFConfig();
        data.deleteAllDatabaseData();
        mApplication.deleteFilesFromDir( new File( config.mCustomAssetPath ) );
        mApplication.nullifyNavMenuAdapter();
        SFAppData.saveSyncTime( 0 );
        mApplication.isSyncing = false;

        Intent intent = new Intent( mApplication , SFMainActivity.class );
        startActivity( intent );
        overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
    }

    private void closeSettingsScreen(){
        onBackPressed();
    }

    @Override
    public void onBackPressed()
    {
        //Prevent going back when doing a full refresh.
        if(mApplication.isDoingFullSync)
        {
            mApplication.makeToast( "Please wait for sync to finish" );
            return;
        }
        if (mApplication.isNavOpen)
        {
            SFSharedUIMethods.closeMenu();
            return;
        }

        this.finish();
        overridePendingTransition( R.anim.sf_activity_slidein_left, R.anim.sf_activity_slideout_right );
    }

    @Override
    public boolean onTouchEvent( MotionEvent event )
    {
        this.mDetector.onTouchEvent( event );
        return super.onTouchEvent( event );
    }

    @Override
    public void onLowMemory()
    {
        super.onLowMemory();
        this.clearCache();
    }
    @Override
    public void onTrimMemory(int level)
    {
        super.onTrimMemory(level);
        this.clearCache();
    }

    public void clearCache()
    {
    }

    @Override
    public boolean dispatchTouchEvent( MotionEvent e )
    {
        if(mApplication.isDoingFullSync)
        {
            return true;
        }
        else
        {
            super.dispatchTouchEvent( e );
        }
        return false;
    }
}



