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.os.AsyncTask;
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.ProgressBar;
import android.widget.TextView;

import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.adapters.SFNavMenuAdapter;
import com.sharefaith.thesharefaithapp.adapters.SFVideoStreamAdapter;
import com.sharefaith.thesharefaithapp.base.SFAppData;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFConfig;
import com.sharefaith.thesharefaithapp.base.SFConstants;
import com.sharefaith.thesharefaithapp.base.SFUtil;
import com.sharefaith.thesharefaithapp.models.SFVideoStreamModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import io.sentry.Sentry;

/**
 * Created by sfwebsitedev on 12/9/16.
 * Activity for showing video stream list
 */

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

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

    //private ArrayList mVideoStreamData;
    private SFVideoStreamModel[] mVideoStreamModels;
    private ListAdapter mAdapter;

    private GestureDetector mDetector;
    private View.OnTouchListener mGestureListener;

    public HashMap<String,String> mStreamData;
    public String mStreamType;
    public String mStreamId;
    public String mStreamContent;


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

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

        //Google Analytics tracking
        mApplication.logScreen("video stream");

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

        //HashMap<String,String> streamData;
        String[] keys = { "source","streamid","content", "url" };
        if( null == mAppData )
        {
            //This should be quite rare. https://sentry.io/sharefaith/android-churchapp/issues/762486541/?query=is:unresolved
            Sentry.capture("Workaround onResume empty mAppData.");
            mApplication.forceSyncScreen();
            return;
        }
        this.mStreamData = mAppData.getMetaData( mApplication.currentSectionPosition, keys );

        if( this.mStreamData.get( "source" ).equals( "Other" ) )
        {
            SFUtil.logSiteEvent( "Opened Link" );
//            Log.d( "mtag","url = " + this.mStreamData.get( "url" ) );
            SFSharedUIMethods.launchDonate( this.mStreamData.get( "url" ) );
            this.finish();
        }

        mStreamContent = "";
        mConfig = new SFConfig();
        int layout = mAppData.getLayout( mApplication.currentVideoStreamPosition );
        SFSharedUIMethods.setBaseView( this, layout );
        loadInterface();
        this.mLoading = (ProgressBar) findViewById( R.id.sf_loading_spinner );
        this.mLoading.setVisibility( View.VISIBLE );
        this.mStreamType = this.mStreamData.get( "source" );
        this.mStreamId = this.mStreamData.get( "streamid" );
//        Log.d( "mtag","current VideoStreamPosition = " + mApplication.currentVideoStreamPosition );
        //this.mStreamContent = this.mStreamData.get( "content" );
//        Log.d( "mtag","stream data = " + this.mStreamContent );
//        if( mStreamContent.length() > 0 )
//        {
////            Log.d( "mtag","loading with save data streamContent = " + mStreamContent );
////            loadVideoData();
////            Log.d( "mtag","first load finished" );
//        }

        DownloadVideoDataTask videoDownloadTask = new DownloadVideoDataTask( this );
        try
        {
            URL url = new URL( SFApplication.getInstance().getResources().getString( R.string.appserve_url ) + "?action=getLiveFeedItems&type=" +
                    mStreamType + "&id=" + mStreamId + "&i=" + SFConstants.UAID_KEY );
            videoDownloadTask.execute( url );
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        }

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

    /**
     * load data for the Video stream list
     */
    public void loadVideoData()
    {
        Log.d( "mtag","videoStreamData: ");
        mApplication.longInfo( "mtag", mStreamContent );


        try
        {
            JSONArray streamDataArray = new JSONArray( mStreamContent );
            this.mVideoStreamModels = new SFVideoStreamModel[streamDataArray.length()];

            for (int i = 0; i < streamDataArray.length(); i++)
            {
                this.mVideoStreamModels[i] = new SFVideoStreamModel( streamDataArray.getJSONObject( i ), this.mStreamData.get( "source" ) );
            }

            this.mAdapter = new SFVideoStreamAdapter( mVideoStreamModels );
            runOnUiThread( new Runnable()
            {
                @Override
                public void run()
                {
                    mGridView = (GridView) findViewById( R.id.slide_right );
                    mLoading.setVisibility( View.GONE );
                    mGridView.setAdapter( mAdapter );

                    mGridView.setOnTouchListener( mGestureListener );
                    mGridView.setOnItemClickListener( new AdapterView.OnItemClickListener()
                    {
                        @Override
                        public void onItemClick( AdapterView<?> parent, View view, int position, long id )
                        {
                            if( mVideoStreamModels[position].mType.equals( "upcoming" ))
                            {
                                return;
                            }
                            if( mVideoStreamModels[position].mSource.equals( "BoxCast" ))
                            {
                                mApplication.launchVideo( mVideoStreamModels[position].mContent );
                            }
                            else
                            {
                                mApplication.sfCurrentVideoStream = mVideoStreamModels[position];
                                Intent intent = new Intent( mApplication.getCurrentActivity(), SFVideoPlayerActivity.class );
                                mApplication.getCurrentActivity().startActivity( intent );
                            }
                        }
                    } );
                }
            } );

        } catch (JSONException e)
        {
            e.printStackTrace();
        }

    }

    @Override
    public void onBackPressed()
    {
        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 );
    }

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

    private class DownloadVideoDataTask extends AsyncTask<URL, Integer, Long>
    {
        public SFVideoStreamActivity mCaller;
        public String mOutputString;

        public DownloadVideoDataTask( SFVideoStreamActivity caller )
        {
            this.mCaller = caller;
            this.mOutputString = "";
        }

        protected Long doInBackground( URL... urls )
        {
            Log.d( "mtag","url = " + urls[0] );
            try
            {
                BufferedReader in = new BufferedReader( new InputStreamReader( urls[0].openStream() ) );
                String line;

                while( ( line = in.readLine() ) != null )
                {
                    if( line.equalsIgnoreCase( "bye" ) )
                    {
                        Log.e( "SOCKET ERROR", "Socket said goodbye" );
                    }
                    //get lines
                    this.mOutputString += line;
                }
                //Log.d( "mTag","results = " + mResult );
                in.close();
                this.mCaller.mStreamContent = this.mOutputString;
            }
            catch( Exception e )
            {
                //String message = SFMainActivity.instance.getString( R.string.file_error ) + e.getLocalizedMessage();
                //SFMainActivity.makeToast( message );
            }
            finally
            {
                JSONObject json = null;
                try
                {
                    json = new JSONObject(mOutputString);
                    mAppData.setStreamData( json.toString() );
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
                mCaller.loadVideoData();
            }
            Log.d( "mtag","finished second load" );

            long totalSize = 0;

            return totalSize;
        }

    } // private class DownloadTask extends AsyncTask<URL, Integer, Long>
}
