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.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

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

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Activity for showing notification history
 */
public class SFInboxActivity extends Activity
{

    private SFApplication mApplication;
    private SFConfig mConfig;

    private GridView mGridView;
    private ListView mMainNavList;
    private ImageView mRefreshButton;
    private ImageView mPlaybutton;
    private ImageView mOpenSettingsButton;

    private ArrayList inboxItemsData;
    private SFInboxItemModel[] mItems;
    private ListAdapter mAdapter;

    private GestureDetector mDetector;
    private View.OnTouchListener mGestureListener;

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        this.requestWindowFeature( Window.FEATURE_NO_TITLE );

        //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 );
            }
        };
        SFUtil.logSiteEvent( "Opened Inbox" );
    }

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

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

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

        mConfig = new SFConfig();
        setContentView( R.layout.sf_inbox_base );

        mGridView = (GridView) findViewById( R.id.slide_right );

        inboxItemsData = SFInboxItemModel.getAll();
        mItems = new SFInboxItemModel[inboxItemsData.size()];
        for( int i = 0; i < mItems.length; i++ )
        {
            mItems[i] = new SFInboxItemModel((HashMap<String, String>) inboxItemsData.get( i ) );
        }
        mAdapter = new SFInboxAdapter( mItems );
        mGridView.setAdapter( mAdapter );
        loadInterface();

        mGridView.setOnTouchListener( mGestureListener );
        mGridView.setOnItemClickListener( new AdapterView.OnItemClickListener()
        {

            @Override
            public void onItemClick( AdapterView<?> parent, View view, int position, long id )
            {
                SFInboxItemModel item = mItems[position];

                if(item.mObjectType.equals( "simple" ))
                {
                        SFSharedUIMethods.notificationOverlay(item.mContent,item.mPayload);
                }

                else if(item.mObjectType.equals( "post" ))
                {
                    openPost( item.mExternalId );
                }

                else if(item.mObjectType.equals("sermon") )
                {
                    openSermon( item.mExternalId );
                }
            }
        } );

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

    public void openLink( String link )
    {
        try
        {
            Intent browser = new Intent( Intent.ACTION_VIEW, Uri.parse( link ) );
            startActivity( browser );
        }
        catch( Exception e )
        {
            Log.d( "URI", "Exception: " + e.getLocalizedMessage() );
        }
    }

    /**
     * Opens the selected post
     * @param externalId
     */
    public void openPost( String externalId )
    {
        //Log.d("mTag","Hit Open Post -----------------");
        SFAppData appData = new SFAppData();
        int sectionId = appData.getPostSectionIdByExternalId( AiSTr.denullifyInt(  externalId ) );
        if(sectionId != -1)
        {
            SFPostModel post = new SFPostModel( sectionId );
            mApplication.setSfCurrentPost( post );
            mApplication.currentPostPosition = appData.getParentPositionForPostSectionId( sectionId );
            if(mApplication.currentPostPosition != -1)
            {
                //Log.d( "mtag", "current post pos = " + mApplication.currentPostPosition );
                SFSharedUIMethods.swapToViewWithTag( "postdetail", mApplication.currentPostPosition );
            }
        }
        else
        {
            SFSharedUIMethods.notificationOverlay( mApplication.getString( R.string.alert_no_content ) ,"" );
        }
    }

    /**
     * Opens the selected Sermon
     * @param externalId
     */
    public void openSermon( String externalId )
    {
        //Log.d("mTag","Hit Open Sermon -----------------");
        SFAppData appData = new SFAppData();
        int sectionId = appData.getPlaylistSectionIdBySermonExternalId( AiSTr.denullifyInt(  externalId ) );
        if(sectionId != -1)
        {
            SFSermonSeriesModel playlist = new SFSermonSeriesModel( sectionId );
            mApplication.setSfCurrentPlaylist( playlist );
            mApplication.currentPlaylistPosition = appData.getParentPositionForPlaylistSectionId( sectionId );
            //Log.d( "mtag", "current playlist pos = " + mApplication.currentPlaylistPosition );
            if (mApplication.currentPlaylistPosition != -1)
            {
                SFSharedUIMethods.swapToViewWithTag( "sermondetail", mApplication.currentPlaylistPosition );
            }
        }
        else
        {
            SFSharedUIMethods.notificationOverlay( mApplication.getString( R.string.alert_no_content ) ,"" );
        }
    }

    /**
     * handles back press
     */
    @Override
    public void onBackPressed()
    {
        if(mApplication.isDoingFullSync)
        {
            mApplication.makeToast( mApplication.getString( R.string.alert_wait_for_download ) );
            return;
        }
        if (mApplication.isNavOpen)
        {
            SFSharedUIMethods.closeMenu();
            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" ) )
                    }
                };
    }

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

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

    @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;
    }
}