package com.nexstreaming.app.apis;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.MediaController;
import android.widget.TextView;

import com.nexstreaming.app.nexplayersample.R;
import com.nexstreaming.app.widget.NexMediaController;
import com.nexstreaming.nexplayerengine.NexContentInformation;
import com.nexstreaming.nexplayerengine.NexEventReceiver;
import com.nexstreaming.nexplayerengine.NexLog;
import com.nexstreaming.nexplayerengine.NexPlayer;
import com.nexstreaming.nexplayerengine.NexVideoView;

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

/**
 * VAST Sample Activity.
 */
public class NexVASTJavaScriptInterface {
    private final static String LOG_TAG = "NexVAST";

    protected WebView               mAdView = null;
    protected Listener              mListener = null;
    private   NexMediaController    mMediaController = null;
    private   NexPlayer             mContentPlayer = null;

    private   boolean               mIsPlayAd = false;
    private   boolean               mReadyToPlay = false;
    private   boolean               mForceToStart = false;
    private   boolean               mPauseAfterReady = false;
    private   int                   mStartTimeMs = 0;

    private static final Handler    mVASTHandler = new Handler();
    private static final Handler    mContentHandler = new Handler();

    public interface Listener {
        void onStartAd();
        void onCompleteAd();
        void onPlayAd(boolean bPlay);
        void onTimeUpdate(int time);
        void onComplete();

    }




    NexVASTJavaScriptInterface(NexPlayer player, WebView adView, Listener l) {
        mContentPlayer = player;
        mAdView = adView;
        mListener = l;

        mPauseAfterReady = true;
        addContentPlayerEventReceiver();
        //prepareContentView();
    }

    public boolean isPlayAd() {
        return mIsPlayAd;
    }

    public void setPlayAd(boolean play) {
        Log.d(LOG_TAG, "[VASTWebView setPlayAd] play : " + play);
        mIsPlayAd = play;
    }

    public void setmMediaController(NexMediaController controller){
        mMediaController = controller;
    }

    protected void addContentPlayerEventReceiver() {
        NexEventReceiver eventReceiver = new NexEventReceiver() {
            @Override
            public void onEndOfContent(NexPlayer mp) {
                NexLog.i(LOG_TAG, "VASTWebView Content was completed.");
                mContentHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // Signals to the SDK that the content is finished. This will allow the SDK to play post-roll ads, if any are loaded via ad rules.
                        mListener.onComplete();
                    }
                });
            }

            @Override
            public void onError(NexPlayer mp, NexPlayer.NexErrorCode errorCode) {
                NexLog.e(LOG_TAG, "VASTWebView onContentError");
                mContentHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // Signals to the SDK that the content is finished. This will allow the SDK to play post-roll ads, if any are loaded via ad rules.
                        mListener.onComplete();
                    }
                });
            }

            @Override
            public void onAsyncCmdComplete(NexPlayer mp, int command, int result, int param1, int param2) {
                NexLog.i(LOG_TAG, "VASTWebView onAsyncCmdComplete:" + command + "," + result);

                switch (command) {
                    case NexPlayer.NEXPLAYER_ASYNC_CMD_OPEN_LOCAL:
                    case NexPlayer.NEXPLAYER_ASYNC_CMD_OPEN_STREAMING:
                        if (result == 0) {
                            mContentHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    NexLog.i(LOG_TAG, "VASTWebView content player start call, PauseAfterReady:" + mPauseAfterReady);
                                    mContentPlayer.start(mStartTimeMs, mPauseAfterReady);
                                }
                            });
                        } else {
                            onError(mp, NexPlayer.NexErrorCode.fromIntegerValue(result));
                        }
                        break;
                    case NexPlayer.NEXPLAYER_ASYNC_CMD_START_LOCAL:
                    case NexPlayer.NEXPLAYER_ASYNC_CMD_START_STREAMING:
                        if (result == 0) {
                            mContentHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (mPauseAfterReady) {
                                        NexLog.i(LOG_TAG, "VASTWebView content player need to pause, PauseAfterReady:" + mPauseAfterReady);
                                        mContentPlayer.pause();
                                        mPauseAfterReady = false;
                                    }
                                }
                            });
                        } else {

                        }
                        break;
                    case NexPlayer.NEXPLAYER_ASYNC_CMD_PAUSE:

                        break;
                    case NexPlayer.NEXPLAYER_ASYNC_CMD_RESUME:
                        break;
                }
            }
        };
        mContentPlayer.addEventReceiver(eventReceiver);
    }




    public void playContent(int startTime){
        mStartTimeMs = startTime;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void pauseContent() {
        mIsPlayAd = true;
        if(mListener != null) {
            mListener.onPlayAd(true);
        }

        Log.d(LOG_TAG, "[VASTWebView pauseContent] Show Ad View");
        mVASTHandler.post(new Runnable() {
            @Override
            public void run() {
                mAdView.setVisibility(View.VISIBLE);
            }
        });
        mContentHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mContentPlayer != null){
                    Log.d(LOG_TAG, "[VASTWebView pauseContent]");
                    mContentPlayer.pause();
                }
            }
        });

    }

    @JavascriptInterface
    public void resumeContent() {

        mIsPlayAd = false;

        if(mListener != null) {
            mListener.onPlayAd(false);
        }
        mVASTHandler.post(new Runnable() {
            @Override
            public void run() {
                Log.d(LOG_TAG, "[VASTWebView resumeContent] Hide Ad View");
                mAdView.setVisibility(View.INVISIBLE);
            }
        });
        mContentHandler.post(new Runnable() {
            @Override
            public void run() {
                Log.d(LOG_TAG, "[VASTWebView resumeContent]");
                if(mReadyToPlay) {
                    mContentPlayer.start(mStartTimeMs,mPauseAfterReady);
                    mReadyToPlay = false;
                } else {
                    mContentPlayer.resume();
                }
            }
        });

    }

    @JavascriptInterface
    public void startAd() {
        if(mListener != null) {
            Log.d(LOG_TAG, "[VASTWebView startAd]");
            mListener.onStartAd();
        }
    }

    @JavascriptInterface
    public void completeAd() {
        Log.d(LOG_TAG, "[VASTWebView completeAd]");
        if(mListener != null) {
            mListener.onCompleteAd();
        }
    }

    @JavascriptInterface
    public void setCuePoints(int[] arrCue) {
        Log.d(LOG_TAG, "[VASTWebView setCuePoints] cue num : " + arrCue.length);

        final int[] cues = arrCue;
        mVASTHandler.post(new Runnable() {
            @Override
            public void run() {
                for(int i=0; i<cues.length; i++) {
                    Log.d(LOG_TAG, "Cue[" + i + "] = " + cues[i] );
                    cues[i] *= 1000;
                }
                mMediaController.setMarkers(cues);
            }
        });
    }
}
