package com.sharefaith.thesharefaithapp.ui;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
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.ScrollView;
import android.widget.TextView;

import com.appideas.base.AiSTr;
import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.adapters.LimitedMapCache;
import com.sharefaith.thesharefaithapp.adapters.SFNavMenuAdapter;
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 com.sharefaith.thesharefaithapp.models.SFPostModel;

import java.io.File;
import java.util.HashMap;

/**
 * Created by Anthony on 2016-1-25.
 *
 * Activity for individual blog posts
 */
public class SFBlogActivity extends Activity
{
    private SFApplication mApplication;
    private SFConfig mConfig;
    private SFAppData mAppData;

    private SFPostModel mPost;

    private TextView mTitle;
    private ImageView mImage;
    private ScrollView mScrollView;
    private WebView mTopWebView;
    private WebView mBottomWebiew;
    private ListView mMainNavList;
    private ImageView mRefreshButton;
    private ImageView mOpenSettingsButton;

    private RelativeLayout mTextSizeContainer;
    private TextView mTextSmall;
    private TextView mTextMedium;
    private TextView mTextLarge;
    private TextView mCurrentTextSizeUnderline;

    private ImageView mPlaybutton;

    private static LimitedMapCache<String, Bitmap> mBitMapCache;
    private BitmapFactory.Options mOptions;

    private GestureDetector mDetector;
    private View.OnTouchListener mGestureListener;

    private boolean mIsSizePickerOpen;
    private boolean mTitleShown;

    private String mFullContent;
    private String mSimpleContent;

    /**
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        this.requestWindowFeature( Window.FEATURE_NO_TITLE );
        setContentView( R.layout.sf_blog_single );

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

        mApplication = SFApplication.getInstance();
        mAppData = new SFAppData();

        //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 Post" );
    }

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

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

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

        mConfig = new SFConfig();

        mTopWebView = (WebView) findViewById( R.id.content_webView );
        mTopWebView.getSettings().setJavaScriptEnabled( true );
        mBottomWebiew = (WebView) findViewById( R.id.bottom_webView );
        mBottomWebiew.getSettings().setJavaScriptEnabled( true );
        mScrollView = (ScrollView) findViewById( R.id.scrollView );

        mPost = mApplication.getSfCurrentPost();

        mTextSizeContainer = (RelativeLayout) findViewById( R.id.size_container );
        mTextSizeContainer.setVisibility( View.GONE );

        mTitle = (TextView) findViewById( R.id.title_textView );
        mImage = (ImageView) findViewById( R.id.header_imageView );
        mTitleShown = true;

        //load the content
        setHeader();
        setContent();

        //setup the nav menu
       // SFNavMenuModel[] menuItems = SFNavMenuModel.getAll();
        loadInterface();

        //setup the flig listeners
        mScrollView.setOnTouchListener( mGestureListener );
        mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {

            @Override
            public void onScrollChanged() {


                int scrollY = mScrollView.getScrollY(); //for verticalScrollView
                //DO SOMETHING WITH THE SCROLL COORDINATES
                if( mTitleShown && scrollY > 1 )
                {
                    mTitleShown = false;
                    setupHeaderImage( -1 );
                    mBottomWebiew.setVisibility( View.VISIBLE );
                    mImage.setVisibility( View.GONE );
                    mTopWebView.setVisibility( View.GONE );
                }

            }
        });

        mTopWebView.setOnLongClickListener( new View.OnLongClickListener()
        {

            @Override
            public boolean onLongClick( View arg0 )
            {
                openSizePicker();
                return true;

            }
        } );
        mTopWebView.setOnTouchListener( mGestureListener );

        mBottomWebiew.setOnLongClickListener( new View.OnLongClickListener()
        {

            @Override
            public boolean onLongClick( View arg0 )
            {
                openSizePicker();
                return true;

            }
        } );
        mBottomWebiew.setOnTouchListener( mGestureListener );

        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" ) );

        setTextSizeUnderline();

        //facebook share button
        /*ShareButton shareButton = (ShareButton) findViewById( R.id.fb_share_button );
        if(mApplication.isFacebookShareEnabled && this.mPost.mWpId != 0)
        {
            //Log.d( "mTag","wpid = " + this.mPost.mWpId );
            ShareLinkContent content = new ShareLinkContent.Builder()
                    .setContentUrl( Uri.parse( "http://sfapp01.sharefaithwebsites.com/hp_wordpress/?p=" + this.mPost.mWpId ) )
                    .build();


            shareButton.setShareContent( content );
        }
        else
        {
            shareButton.setVisibility( View.GONE );
        }*/

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

    /**
     * open the size picker settings menu
     */
    private void openSizePicker()
    {
        if(!mIsSizePickerOpen)
        {
            Animation animation = AnimationUtils.loadAnimation( this, R.anim.sf_menu_expand_up );
            mTextSizeContainer.startAnimation( animation);
            mTextSizeContainer.setVisibility( View.VISIBLE );
            mIsSizePickerOpen = true;
        }
    }

    /**
     * close the size picker setting menu
     */
    private void closeSizePicker()
    {
        Animation animation = AnimationUtils.loadAnimation( this, R.anim.sf_menu_collapse_down );
        mTextSizeContainer.startAnimation( animation );
        mTextSizeContainer.setVisibility( View.GONE );
        mIsSizePickerOpen = false;
    }

    /**
     * set the state of the size picker menu items
     */
    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 );
        }
    }

    /**
     * setup the listener for the size picker menu
     * @param action
     * @return
     */
    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();
                        closeSizePicker();
                        }

                };
    }

    /**
     * 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" ) )
                    }
                };
    }

    /**
     * handle back button
     */
    @Override
    public void onBackPressed()
    {
        if(mApplication.isDoingFullSync)
        {
            mApplication.makeToast( "Please wait for sync to finish" );
            return;
        }
        if (mApplication.isNavOpen)
        {
            SFSharedUIMethods.closeMenu();
            return;
        }
        if(mIsSizePickerOpen)
        {
            closeSizePicker();
            return;
        }


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

    /**
     * handle pause of activity
     */
    @Override
    public void onPause()
    {
        super.onPause();
        mTopWebView.onPause();
        mBottomWebiew.onPause();
        this.finish();
    }

    /**
     * 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" ) )
                        {
                            finish();
                            overridePendingTransition( R.anim.sf_activity_slidein_left, R.anim.sf_activity_slideout_right );
                            return;
                        } // if( action.equals( "opennav" ) )
                        else 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();
        }
    }

    /**
     * setup the exit post button
     */
    private void layoutSetup()
    {
        ImageButton button = (ImageButton) findViewById( R.id.openMenuImageButton );
        button.setPadding( 0, mApplication.getDP( 10 ), 0, mApplication.getDP( 10 ) );
        button.setImageResource( R.drawable.sf_control_x_regular );
    }

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

    /**
     * setup the Header of the post
     */
    private void setHeader()
    {
        //set content of header

        int layout = mAppData.getLayout( mApplication.currentPostPosition );
        boolean isTitlesEnabled = mAppData.getIsTitleEnabled( mApplication.currentPostPosition );
        setupHeaderImage( layout );

        File currentThumbnail = new File( mConfig.mCustomAssetPath + mPost.mThumbnail );

        int memMB = ((ActivityManager)mApplication.getSystemService( Context.ACTIVITY_SERVICE )).getMemoryClass();
        mBitMapCache = new LimitedMapCache<String,Bitmap> ( memMB/2 );
        mOptions = SFUtil.commonImgOpt();

        if( mPost != null ) //Set the variable things, title and excerpt, even if not creating.
        {
            String showTitle = SFUtil.stripHtml( mPost.mTitle ).toString();
            if( mTitle != null )
            {
                if(showTitle.equals( "" )|| !isTitlesEnabled )
                {
                    //if layout is nook show title
                    if( !showTitle.equals( "" ) && layout == 1 )
                    {
                        mTitle.setText( showTitle );
                        mTitle.setVisibility( View.VISIBLE );
                    }
                    //if gamut layout and no image show title
                    else if(layout == 0 && !showTitle.equals( "" ) && mPost.mThumbnail.length() <1)
                    {
                        mTitle.setText( showTitle );
                        mTitle.setVisibility( View.VISIBLE );
                    }
                    else
                    {
                        mTitle.setVisibility( View.GONE );
                    }
                }
                else
                {
                    mTitle.setText( showTitle );
                    mTitle.setVisibility( View.VISIBLE );
                }
            }


            //Must consider cases where the view was recycled.
            if( mPost.mThumbnail.length() > 0 && currentThumbnail.exists())
            {
                //The view has different img.
                File imageFile = currentThumbnail;
                String fileStr = currentThumbnail.getAbsolutePath();

                Bitmap bitmap = mBitMapCache.get(fileStr);
                if (null == bitmap)
                {
                    try {
                        bitmap = BitmapFactory.decodeFile( fileStr, mOptions );
                        mBitMapCache.add(fileStr, bitmap);
                    }
                    catch (OutOfMemoryError e)
                    {
                        System.gc();
                        bitmap = BitmapFactory.decodeFile(fileStr, mOptions);
                    }
                }
                mImage.setImageBitmap(bitmap);
                mImage.setVisibility( View.VISIBLE );
            }
            else
            {
                mImage.setImageBitmap( null );
                if(layout == 0)
                {
                    mImage.setVisibility( View.INVISIBLE );
                }
                else
                {
                    mImage.setVisibility( View.GONE );
                }
            }
        }
    }

    /**
     * set the content of the blog
     */
    private void setContent()
    {
        mFullContent = mPost.mContent;
        //mApplication.longInfo( "mTag","blog content = " + content );
        if( mFullContent == null )
        {
            mFullContent = "";
            mSimpleContent = "";
        }
        mSimpleContent = AiSTr.stripImagesHTML( mFullContent );
        HashMap<String,String> envelope = SFUtil.htmlEnvelope();
        mTopWebView.loadDataWithBaseURL(null, envelope.get( "head" ) + mSimpleContent + envelope.get( "tail" ), "text/html; charset=UTF-8", null,null );
        mBottomWebiew.loadDataWithBaseURL(null, envelope.get( "head" ) + mFullContent + envelope.get( "tail" ), "text/html; charset=UTF-8", null ,null);

    }

    /**
     * Get the view based on the layout type the user has chosen
     * @return
     */
    private View setupHeaderImage(int layout)
    {
        if(layout != -1)
        {
            if (layout == 0)
            {
                mTitle.setVisibility( View.GONE );
                mTitle = (TextView) findViewById( R.id.gamut_title );
            } else if (layout == 1)
            {
                ViewGroup.LayoutParams list = mImage.getLayoutParams();
                list.width = list.height;
                mImage.setLayoutParams( list );
                ViewGroup.MarginLayoutParams marginList = (ViewGroup.MarginLayoutParams) mImage.getLayoutParams();
                marginList.topMargin = mApplication.getDP( 20 );
                marginList.bottomMargin = mApplication.getDP( 10 );
                mImage.setLayoutParams( list );

            } else if (layout == 2)
            {
                ViewGroup.LayoutParams list = mImage.getLayoutParams();
                int height = list.height;
                float width = (float) (height * 1.33);
                //Log.d( "mTag", "width = " + width +": height = " + height);
                list.width = (int) width;
                mImage.setLayoutParams( list );
                ViewGroup.MarginLayoutParams marginList = (ViewGroup.MarginLayoutParams) mImage.getLayoutParams();
                marginList.topMargin = mApplication.getDP( 20 );
                marginList.bottomMargin = mApplication.getDP( 10 );
                mImage.setLayoutParams( list );
            }
        }
        else
        {

            mTitle.setVisibility( View.GONE );
            mTitle = (TextView) findViewById( R.id.title_textView );
            mTitle.setText( SFUtil.stripHtml( mPost.mTitle ).toString() );
            mTitle.setVisibility( View.VISIBLE );

        }
        return null;
    }

    /**
     * capture touch events when doing full sync
     * @param e
     * @return
     */
    @Override
    public boolean dispatchTouchEvent( MotionEvent e )
    {
        if(mApplication.isDoingFullSync)
        {
            return true;
        }
        else
        {
            super.dispatchTouchEvent( e );
        }
        return false;
    }

}
