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.GridView;
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.SFEventAdapter;
import com.sharefaith.thesharefaithapp.adapters.SFMonthAdapter;
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.models.SFCalendarEventModel;
import com.sharefaith.thesharefaithapp.models.SFMonthModel;

import java.util.Calendar;
import java.util.Locale;


public class SFCalendarActivity extends Activity
{
    private SFApplication mApplication;
    private SFAppData mAppData;
    private SFConfig mConfig;

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

    private GestureDetector mDetector;
    private View.OnTouchListener mGestureListener;

    private Calendar mCalendar;
    private SFMonthModel mMonthModel;
    public SFMonthAdapter mMonthAdapter;
    public SFEventAdapter mEventAdapter;

    //calendar views
    private TextView mTextViewMonth;
    private ImageView mNextMonth;
    private ImageView mPrevMonth;

    //calendar event list views
    public RelativeLayout mEventListContainer;
    private ListView mEventList;
    private ImageView mCloseEventList;

    //calendar event details views
    private RelativeLayout mEventDetailsContainer;
    private ImageView mCloseEventDetails;
    private TextView mEventDetailsTitle;
    private TextView mEventDetailsDate;
    private TextView mEventDetailsDescription;
    private TextView mEventDetailsLocation;

    //calendar flags
    public boolean mIsEventListOpen;
    public boolean mIsEventDetailsOpen;

    private String mEventData;

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

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

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

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

        mApplication.setCurrentActivity( this );
        mApplication.currentViewTag = "calendar";
        //Log.d("mTag","current more pos = " + mApplication.currentMorePosition );
        if(mApplication.currentCalendarPosition == -2)
        {
            //Log.d( "mTag","Hit inside if pos = -2" );
            this.finish();
            return;
        }
        mApplication.currentSectionPosition = mApplication.currentCalendarPosition;

        mConfig = new SFConfig();
        mEventData = mAppData.getEventData();
        mCalendar = Calendar.getInstance();

        mApplication.setCurrentCalendar();

        mTextViewMonth = (TextView) findViewById( R.id.textView_month_name );
        mNextMonth = (ImageView) findViewById( R.id.imageView_nextMonth );
        mNextMonth.setOnClickListener( this.changeMonthListener( "nextMonth" ) );
        mPrevMonth = (ImageView) findViewById( R.id.imageView_prevMonth );
        mPrevMonth.setOnClickListener( this.changeMonthListener( "prevMonth" ) );
        mGridviewCalendar = (GridView) findViewById( R.id.gridview_calendar );
        mEventListContainer = (RelativeLayout) findViewById( R.id.calendar_events );
        mEventList = (ListView) findViewById( R.id.event_list );
        mCloseEventList = (ImageView) findViewById( R.id.imageView_close_list );
        mCloseEventList.setOnClickListener( closeEventPanel( "list" ) );

        //event details views
        mEventDetailsContainer = (RelativeLayout) findViewById( R.id.event_details );
        mCloseEventDetails = (ImageView) findViewById( R.id.imageView_close_details );
        mCloseEventDetails.setOnClickListener( closeEventPanel( "details" ) );
        mEventDetailsTitle = (TextView) findViewById( R.id.textView_title_details );
        mEventDetailsDate = (TextView) findViewById( R.id.textView_date_details );
        mEventDetailsDescription = (TextView) findViewById( R.id.textView_description_details );
        mEventDetailsLocation = (TextView) findViewById( R.id.textView_location_details );

        mIsEventListOpen = false;
        mIsEventDetailsOpen = false;
        mApplication.activeYearIndex = 0;

        loadCalendar();
        loadInterface();

        //load the event list with the current day's events
        //Log.d( "mtag","currentDay index = " + mApplication.currentDayIndex );
        mMonthAdapter.setActiveDay( (mApplication.currentDayIndex) -1,mMonthModel.mPreMonthDays );

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

    /**
     * load the Calendar
     */
    public void loadCalendar()
    {
        this.mTextViewMonth.setText( this.mCalendar.getDisplayName( Calendar.MONTH,Calendar.LONG, Locale.getDefault()) +
                "  " + this.mCalendar.get( Calendar.YEAR ) );
        //Log.d("mtag","load Calendar event data = " + mEventData);
        this.mMonthModel = new SFMonthModel( this.mCalendar, mEventData );
        this.mMonthAdapter = new SFMonthAdapter( this.mMonthModel.mDayModels );
        this.mGridviewCalendar.setAdapter( this.mMonthAdapter );
        this.mMonthAdapter.notifyDataSetChanged();
        this.mGridviewCalendar.invalidate();
        this.checkMinMaxMonth();

        //Log.d("mTag","month = " + this.mCalendar.get(Calendar.MONTH) );
    }

    /**
     * checks if it is at the min -3 months or max +12 months and sets month nav buttons accordingly
     */
    private void checkMinMaxMonth()
    {
        if ( mCalendar.get( Calendar.MONTH ) == mApplication.minMonthIndex && mCalendar.get( Calendar.YEAR ) == mApplication.minYearIndex )
        {
            mPrevMonth.setVisibility( View.GONE );
        }
        else
        {
            mPrevMonth.setOnClickListener( changeMonthListener( "prevMonth" ) );
            mPrevMonth.setVisibility( View.VISIBLE );
        }
        if ( mCalendar.get( Calendar.MONTH ) == mApplication.maxMonthIndex && mCalendar.get( Calendar.YEAR ) == mApplication.maxYearIndex )
        {
            mNextMonth.setVisibility( View.GONE );
        }
        else
        {
            mNextMonth.setOnClickListener( changeMonthListener( "nextMonth" ) );
            mNextMonth.setVisibility( View.VISIBLE );
        }
    }
    /**
     * OnClickListener for the navigation bar
     * @param action
     * @return
     */
    private View.OnClickListener changeMonthListener( final String action )
    {
        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {
                        mNextMonth.setOnClickListener( null );
                        mPrevMonth.setOnClickListener( null );
                        mNextMonth.setVisibility( View.GONE );
                        mPrevMonth.setVisibility( View.GONE );
                        if( action.equals( "nextMonth" ) )
                        {
                            nextMonth();
                        }
                        if( action.equals( "prevMonth" ) )
                        {
                            prevMonth();
                        }
                    }
                };
    }
    /**
     * OnClickListener for the navigation bar
     * @param action
     * @return
     */
    private View.OnClickListener closeEventPanel( final String action )
    {
        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {
                        if( action.equals( "list" ) )
                        {
                           closeEventList();
                        }
                        if( action.equals( "details" ) )
                        {
                            closeEventDetails();
                        }
                    }
                };
    }

    /**
     * load the next month
     */
    private void nextMonth()
    {
        //Log.d("mTag","month = " + this.mCalendar.get(Calendar.MONTH) );
        this.mCalendar.add(Calendar.MONTH, 1);
        //Log.d("mTag","month = " + this.mCalendar.get(Calendar.MONTH) );
        loadCalendar();
    }

    /**
     * load the previous month
     */
    private void prevMonth()
    {
        this.mCalendar.add(Calendar.MONTH, -1);
        loadCalendar();
    }

    /**
     * populate the data for the event details
     * @param eventModel
     */
    public void populateEventDetails( SFCalendarEventModel eventModel)
    {
        this.mEventDetailsTitle.setText( eventModel.mTitle );
        this.mEventDetailsDescription.setText( eventModel.mDescription );

        final String location = eventModel.mLocation;
        this.mEventDetailsLocation.setText( location );
        this.mEventDetailsLocation.setOnClickListener( new View.OnClickListener()
        {
            @Override
            public void onClick( View v )
            {
                try
                {
                    //log Analytics
                    mApplication.logEvent( "leave_app","location" );
                    Activity currentActivity = mApplication.getCurrentActivity();
                    Intent i = new Intent( Intent.ACTION_VIEW, Uri.parse( "http://maps.google.com/maps?q=" + location ) );
                    currentActivity.startActivity( i );
                }
                catch( Exception e )
                {
                    Log.d( "MAP", "Exception: " + e.getLocalizedMessage() );
                }
            }
        } );

        Calendar tempCalendar = Calendar.getInstance();
        tempCalendar.set(Calendar.YEAR, mApplication.activeYearIndex);
        tempCalendar.set(Calendar.MONTH, mApplication.activeMonthIndex);
        tempCalendar.set(Calendar.DAY_OF_MONTH, mApplication.activeDayIndex);

        this.mEventDetailsDate.setText( tempCalendar.getDisplayName( Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault() ) +
            ", " + tempCalendar.getDisplayName( Calendar.MONTH, Calendar.SHORT, Locale.getDefault() ) + " " +
                tempCalendar.get( Calendar.DAY_OF_MONTH ) + ", " + tempCalendar.get( Calendar.YEAR ) + eventModel.mDate );
        tempCalendar = null;

        this.mEventDetailsContainer.setVisibility( View.VISIBLE );
        this.mEventDetailsContainer.setOnClickListener( closeEventPanel( "details" ) );
        this.mIsEventDetailsOpen = true;
    }

    /**
     * populate the list of events
     * @param events
     * @param setVisible
     */
    public void populateEventList( SFCalendarEventModel[] events, boolean setVisible )
    {
        //Log.d( "mtag","Hit populateEventList" );
        this.mEventAdapter = new SFEventAdapter( events );
        if( mEventAdapter != null && mEventAdapter.getCount() > 0  )
        {
            this.mEventList.setAdapter( this.mEventAdapter );
            this.mEventAdapter.notifyDataSetChanged();
            if(setVisible)
            {
                this.mEventListContainer.setVisibility( View.VISIBLE );
            }
            this.mEventListContainer.setOnClickListener( closeEventPanel( "list" ) );
            this.mIsEventListOpen = true;
        }
    }

    /**
     * close the list of events
     */
    private void closeEventList()
    {
        mEventListContainer.setVisibility( View.GONE );
        mIsEventListOpen = false;
    }

    /**
     * close the event's details
     */
    private void closeEventDetails()
    {
        mEventListContainer.setVisibility( View.VISIBLE );
        mEventDetailsContainer.setVisibility( View.GONE );
        mIsEventDetailsOpen = false;
    }

    /**
     * handle back press
     */
    @Override
    public void onBackPressed()
    {
        if(mApplication.isDoingFullSync)
        {
            mApplication.makeToast( "Please wait for sync to finish" );
            return;
        }
        if (mApplication.isNavOpen)
        {
            SFSharedUIMethods.closeMenu();
            return;
        }
        if( mIsEventDetailsOpen )
        {
            closeEventDetails();
            return;
        }
        if( mIsEventListOpen )
        {
            closeEventList();
            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();
        }
    }

    /**
     * setup the layout
     */
    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;
    }
}
