package com.sharefaith.thesharefaithapp.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.adapters.SFNavMenuAdapter;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFConfig;
import com.sharefaith.thesharefaithapp.base.SFUtil;

import java.util.HashMap;

import io.sentry.Sentry;

/**
 * Created by Anthony on 1/26/16.
 * Activity for Contact screen
 */
public class SFContactActivity extends Activity
{
    private SFApplication mApplication;
    private SFConfig mConfig;

    private RelativeLayout mSlideRight;
    private ListView mMainNavList;
    private WebView mWebView;

    private RelativeLayout mTextSizeContainer;
    private TextView mTextSmall;
    private TextView mTextMedium;
    private TextView mTextLarge;
    private TextView mCurrentTextSizeUnderline;
    private ImageView mPlaybutton;
    private ImageView mRefreshButton;
    private ImageView mOpenSettingsButton;

    private HashMap<String,String> mConnectMeta;

    private GestureDetector mDetector;
    private View.OnTouchListener mGestureListener;

    private boolean mIsSizePickerOpen;

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        this.requestWindowFeature( Window.FEATURE_NO_TITLE );
        setContentView( R.layout.sf_contact_base );
        //if not tablet keep screen from rotating
        if( !SFConfig.isTablet() )
        {
            setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
        }

        mApplication = SFApplication.getInstance();

        //gesture detection
        mDetector = new GestureDetector( this, new SFGestureListener() );
        mGestureListener = new View.OnTouchListener()
        {
            public boolean onTouch( View v, MotionEvent event )
            {
                return mDetector.onTouchEvent( event );
            }
        };

        mIsSizePickerOpen = false;
        SFUtil.logSiteEvent( "Opened Connect" );

    }

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

        //Google Analytics tracking
        mApplication.logScreen("connect");

        mApplication.setCurrentActivity( this );
        mApplication.currentViewTag = "contact";
        if(mApplication.currentConnectPosition == -2)
        {
            this.finish();
            return;
        }
        mApplication.currentSectionPosition = mApplication.currentConnectPosition;

        mConfig = new SFConfig();

        try {
            mConnectMeta = mApplication.getSFConnectContentMeta(mApplication.currentConnectPosition);
        } catch( ArrayIndexOutOfBoundsException aiee)
        {
            //This should be quite rare. https://sentry.io/sharefaith/android-churchapp/issues/451939856/
            Sentry.capture("Workaround onResume ContactActivity Invalid Array");
            mApplication.forceSyncScreen();
            return;
        }
        //SFNavMenuModel[] menuItems = SFNavMenuModel.getAll();
        loadInterface();

        mSlideRight = (RelativeLayout) findViewById( R.id.slide_right );
        mSlideRight.setOnTouchListener( mGestureListener );
        mWebView = (WebView) findViewById( R.id.connect_webView );
        mWebView.setOnLongClickListener( new View.OnLongClickListener()
        {

            @Override
            public boolean onLongClick( View arg0 )
            {
                mTextSizeContainer.setVisibility( View.VISIBLE );
                mIsSizePickerOpen = true;
                return false;

            }
        } );

        mTextSmall = (TextView) findViewById( R.id.size_small );
        mTextMedium = (TextView) findViewById( R.id.size_medium );
        mTextLarge = (TextView) findViewById( R.id.size_large );

        mTextSmall.setOnClickListener( settingsListener( "size_small" ) );
        mTextMedium.setOnClickListener( settingsListener( "size_medium" ) );
        mTextLarge.setOnClickListener( settingsListener( "size_large" ) );

        setContent();
        setupButtons();

        mTextSizeContainer = (RelativeLayout) findViewById( R.id.size_container );

        setTextSizeUnderline();

        //setup the audio controls or hide if nothing playing
        SFSharedUIMethods.setAudioControls();
        mPlaybutton = (ImageView) findViewById( R.id.playcontrol_play_button );
        mPlaybutton.setOnClickListener( audioControlsListener( "playbutton" ) );
        //mWebView.invalidate();
        //mWebView.reload();
        setContent();
        mApplication.didResume(mConfig);
    }

    private void setTextSizeUnderline()
    {
        if(mApplication.getFontSize().equals( "size_small" ))
        {
            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline1 );
            mCurrentTextSizeUnderline.setVisibility( View.VISIBLE );
        }
        else if(mApplication.getFontSize().equals( "size_large" ))
        {
            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline3 );
            mCurrentTextSizeUnderline.setVisibility( View.VISIBLE );
        }
        else
        {
            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline2 );
            mCurrentTextSizeUnderline.setVisibility( View.VISIBLE );
        }
    }

    private View.OnClickListener settingsListener( final String action )
    {
        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {


                        mCurrentTextSizeUnderline.setVisibility( View.INVISIBLE );
                        if (action.equals( "size_small" ))
                        {
                            mApplication.setFontSize( "size_small" );
                            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline1 );
                        }
                        else if (action.equals( "size_medium" ))
                        {
                            mApplication.setFontSize( "size_medium" );

                            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline2 );
                        }
                        else if (action.equals( "size_large" ))
                        {
                            mApplication.setFontSize( "size_large" );
                            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline3 );
                        }
                        mCurrentTextSizeUnderline.setVisibility( View.VISIBLE );
                        setContent();
                        mTextSizeContainer.setVisibility( View.GONE );
                        mIsSizePickerOpen = false;
                    }

                };
    }

    /**
     * OnClickListener for the audio controls
     * @param action
     * @return
     */
    private View.OnClickListener audioControlsListener( final String action )
    {
        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {
                        if( action.equals( "playbutton" ) )
                        {
                            if( mApplication.getSfMediaPlayer().isPlaying())
                            {
                                mApplication.pauseMediaPlayer();
                                mPlaybutton.setImageResource( R.drawable.audio_play );
                                if(mApplication.isBiblePlaying)
                                {
                                    mApplication.isBibleAudioPaused = true;
                                    mApplication.logEvent( "bible_audio","pause" );
                                }
                                if(mApplication.isSermonPlaying)
                                {
                                    mApplication.isSermonPaused = true;
                                }
                            }
                            else
                            {
                                mApplication.startMediaPlayer();
                                mPlaybutton.setImageResource( R.drawable.audio_pause );
                                if(mApplication.isBiblePlaying)
                                {
                                    mApplication.isBibleAudioPaused = false;
                                    mApplication.logEvent( "bible_audio","play" );
                                }
                                if(mApplication.isSermonPlaying)
                                {
                                    mApplication.isSermonPaused = false;
                                }
                            }
                        } // if( action.equals( "playbutton" ) )
                    }
                };
    }

    @Override
    public void onBackPressed()
    {
        if(mApplication.isDoingFullSync)
        {
            mApplication.makeToast( "Please wait for sync to finish" );
            return;
        }
        if (mApplication.isNavOpen)
        {
            SFSharedUIMethods.closeMenu();
            return;
        }
        if(mIsSizePickerOpen)
        {
            mTextSizeContainer.setVisibility( View.GONE );
            mIsSizePickerOpen = false;
            return;
        }

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

    /**
     * OnClickListener for the navigation bar
     * @param action
     * @return
     */
    private View.OnClickListener navItemListener( final String action )
    {
        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {
                        if( action.equals( "opennav" ) )
                        {
                            if( !mApplication.isNavOpen )
                            {
                                SFSharedUIMethods.openMenu();
                            }
                            else
                            {
                                SFSharedUIMethods.closeMenu();
                            }

                        } // if( action.equals( "opennav" ) )
                        if( action.equals( "listennav" ) )
                        {

                            if( mApplication.isNavOpen )
                            {
                                SFSharedUIMethods.closeMenu();
                            }

                            Intent intent = new Intent( mApplication.getCurrentActivity(), SFDownloadsActivity.class  );
                            startActivity( intent );
                            overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
                        } // if( action.equals( "opennav" ) )
                    }
                };
    }

    /**
     * Load the UI elements
     */
    private void loadInterface()
    {
        SFConfig config = new SFConfig();
        // Get the basic layout components going
        LinearLayout titleBarLayout = (LinearLayout) findViewById( R.id.navMenuContainer );
        titleBarLayout.setBackgroundColor( Color.parseColor( "#" + config.mNavColor ) );

        // Set the title bar properties
        TextView titleBarView = (TextView) findViewById( R.id.navMenuTitle );
        titleBarView.setText( config.mAppTitle );

        ImageButton openNav = (ImageButton) findViewById( R.id.openMenuImageButton );
        openNav.setOnClickListener( this.navItemListener( "opennav" ) );

        ImageButton listenNav = (ImageButton) findViewById( R.id.openListenImageButton );
        listenNav.setOnClickListener( this.navItemListener( "listennav" ) );

        // create the main navigation menu items
        this.mMainNavList = (ListView) findViewById( R.id.mainNavListView );
        SFNavMenuAdapter navMenuAdapter = SFApplication.getInstance().getSfNavMenuAdapter();
        this.mMainNavList.setOnItemClickListener( navMenuAdapter.handleTap( this ) );
        this.mMainNavList.setAdapter( mApplication.getSfNavMenuAdapter() );

        layoutSetup();

        mRefreshButton = (ImageView) findViewById( R.id.refreshArrows );
        int iconColor = Color.parseColor( "#" + this.mConfig.customFontColorForNavColor() );
        mRefreshButton.setColorFilter( iconColor, PorterDuff.Mode.MULTIPLY );
        mRefreshButton.setOnTouchListener(new View.OnTouchListener() {
            long then = 0;
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if(event.getAction() == MotionEvent.ACTION_DOWN)
                {
                    this.then = System.currentTimeMillis();
                    return true;
                }
                else if(event.getAction() == MotionEvent.ACTION_UP)
                {
                    if((System.currentTimeMillis() - this.then) > 5000)
                    {
                        SFSharedUIMethods.fullrefresh();
                    }
                    else
                    {
                        SFSharedUIMethods.refresh();
                    }
                }
                return false;
            }
        });

        //Setup the settings button on menu footer
        mOpenSettingsButton = (ImageView) findViewById( R.id.openSettingsButton );
        mOpenSettingsButton.setColorFilter( iconColor, PorterDuff.Mode.MULTIPLY );
        mOpenSettingsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick( View v )
            {
                SFSharedUIMethods.closeMenu();
                Intent intent = new Intent( mApplication, SFSettingsActivity.class );
                startActivity( intent );
                overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
            }
        });

        if(mApplication.isSyncing)
        {
            SFSharedUIMethods.animateRefresh();
        }
    }

    private void layoutSetup()
    {
        ImageButton button = (ImageButton) findViewById( R.id.openMenuImageButton );
        button.setBackgroundResource( R.drawable.openmenu );
    }

    /**
     * Handles gesture touch events
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent( MotionEvent event )
    {
        this.mDetector.onTouchEvent( event );
        return super.onTouchEvent( event );
    }

    /**
     * Set up the content for the Activity
     */
    private void setContent()
    {
        //mWebView.clearView();
        //mWebView.setVisibility( View.INVISIBLE );
        String content = "";
        if( mConnectMeta.containsKey( "content" ) )
        {
            content = mConnectMeta.get( "content" );
        }
        //Log.d( "mTag","content = " + content );
        HashMap<String,String> envelope = SFUtil.htmlEnvelope( );

        mWebView.loadDataWithBaseURL(null,envelope.get( "head" ) + content + envelope.get( "tail" ), "text/html; charset=UTF-8", null,null );
        mWebView.setAlpha( 1f );
        mWebView.setOnTouchListener( mGestureListener );
        //mWebView.invalidate();
        //mWebView.setVisibility( View.VISIBLE );
        //mWebView.reload();
        //Log.d( "mTag","hit end of set content " );
    }

    /**
     * Setup the connect buttons
     */
    private void setupButtons()
    {
        SFConfig config = new SFConfig();

        int colorInt = Color.parseColor( "#ff" + config.mNavColor );

        ImageView[] buttons =
                {
                        (ImageView) findViewById( R.id.sfFacebookImageView ),
                        (ImageView) findViewById( R.id.sfTwitterImageView ),
                        (ImageView) findViewById( R.id.sfEmailImageView ),
                        (ImageView) findViewById( R.id.sfPhoneImageView )
                };
        String[] urls ={"","","",""};
        try
        {
            urls[0] = mConnectMeta.get( "facebook" );
            urls[1] = mConnectMeta.get( "twitter" );
            urls[2] = mConnectMeta.get( "email" );
            urls[3] = mConnectMeta.get( "phone" );
        }
        catch (Exception e)
        {

            e.printStackTrace();
        }
        for( int i = 0; i < buttons.length; i++ )
        {
            buttons[i].setColorFilter( Color.parseColor( "#" + this.mConfig.customFontColorForNavColor() ) );
            //Log.d("mTag","urls length = " +urls.length + "url " + i + " = " + urls[i]);
            if( urls[i] == null || urls[i].length() < 1 ) // set buttons without the required info to disabled
            {
                buttons[i].setAlpha( (float)0.3 );
                buttons[i].setClickable( false );
            }
            else
            {
                buttons[i].setAlpha( (float)1.0 );
                buttons[i].setClickable( true );
            }
        }

    }


    /**
     * Handles click events for the link buttons
     * @param view
     */
    public void simpleTapHandler( View view )
    {
        int viewId =  view.getId();
        HashMap<Integer,String> map = simpleTagsForViews();

        String action = map.get( viewId );
        if( action == null )
        {
            action = "unknown";
        }

        // easier ones first
        if( action == "sfImage" || action == "sfFrame" )
        {
            mApplication.logEvent( "leave_app","shaerfaith" );
            SFUtil.logSiteEvent( "Launch Sharefaith" );
            String url = "http://www.sharefaith.com/category/church-websites.html";
            Intent browser = new Intent( Intent.ACTION_VIEW, Uri.parse( url ) );
            startActivity( browser );
            return;
        }
        else if( action == "sfAppImage" || action == "sfAppFrame" )
        {
            mApplication.logEvent( "leave_app","sharefaith" );
            SFUtil.logSiteEvent( "Launch Sharefaith App" );
            String url = "http://www.sharefaith.com/category/church-app.html";
            Intent browser = new Intent( Intent.ACTION_VIEW, Uri.parse( url ) );
            startActivity( browser );
            return;
        }
        else
        {

            String url = mConnectMeta.get( action );
            if( url == null ) // For now, all actions must have a corresponding content meta key
            {
                return;
            }

            if( action == "facebook" )
            {
                mApplication.logEvent( "leave_app","facebook" );
                SFUtil.logSiteEvent( "Launch " + action );
                Intent browser = SFUtil.getFacebookIntent( url.trim(), this );
                startActivity( browser );

            }
            else if( action == "twitter" )
            {
                mApplication.logEvent( "leave_app","twitter" );
                SFUtil.logSiteEvent( "Launch " + action );
                Intent browser = new Intent( Intent.ACTION_VIEW, Uri.parse( url.trim() ) );
                startActivity( browser );
            }
            else if( action == "email" )
            {
                mApplication.logEvent( "leave_app","email" );
                SFUtil.logSiteEvent( "Launch email" );
                Intent browser = new Intent( Intent.ACTION_SENDTO, Uri.parse( "mailto:" + url.toString() ) );
                startActivity( Intent.createChooser( browser, getString( R.string.send_email ).toUpperCase().toUpperCase() ) );
            }
            else if( action == "phone" )
            {
                mApplication.logEvent( "leave_app","phone" );
                SFUtil.logSiteEvent( "Launch phone" );
                Intent browser = new Intent( Intent.ACTION_DIAL, Uri.parse( "tel:" + url.trim() ) );
                startActivity( browser );
            }

        }
    }

    /**
     * Simplify the translation of View.id to something a human can parse
     */
    private static HashMap<Integer,String> simpleTagsForViews()
    {
        HashMap<Integer,String> returnValue = new HashMap<Integer,String>();

        returnValue.put( R.id.sfFacebookImageView, "facebook" );
        returnValue.put( R.id.sfTwitterImageView, "twitter" );
        returnValue.put( R.id.sfEmailImageView, "email" );
        returnValue.put( R.id.sfPhoneImageView, "phone" );
        returnValue.put( R.id.sfLogoFrame, "sfFrame" );
        returnValue.put( R.id.sfLogoFrame, "sfFrame" );
        returnValue.put( R.id.sfButtonRelativeLayout,  "sfAppFrame" );
        returnValue.put( R.id.sfLogoImageView,  "sfAppImage" );

        return returnValue;
    }

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

}
