package com.nexstreaming.app.apis;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.nexstreaming.app.nexplayersample.R;
import com.nexstreaming.app.nxb.info.NxbInfo;
import com.nexstreaming.app.widget.NexMediaController;
import com.nexstreaming.nexplayerengine.NexContentInformation;
import com.nexstreaming.nexplayerengine.NexPlayer;
import com.nexstreaming.nexplayerengine.NexVideoView;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * VAST Sample Activity.
 */
public class NexVASTWebViewSample extends AppCompatActivity implements NexVASTJavaScriptInterface.Listener{
    private final static String LOG_TAG = "NexVASTWVSample";

    private NexVideoView mVideoView = null;
    private Activity mActivity = null;
    private Uri mCurrentUri = null;
    private ArrayList<File> mLocalFileList = null;
    private String mCurrentPath = null;
    private int mCurrentIndex = 0;
    private TextView mErrorTextView = null;

    private NexVASTJavaScriptInterface mJSInterface = null;
    private NexMediaController mMediaController = null;
    private WebView mAdView = null;
    private boolean mCompleteAd = false;
    private boolean mCompleteContent = false;
    private static final Handler mHandler = new Handler();

    private class WebChromeClientCustomPoster extends WebChromeClient {

        @Override
        public Bitmap getDefaultVideoPoster() {
            return Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i(LOG_TAG, "onCreate");
        mActivity = this;
        preloadLibs();
        getIntentExtra(getIntent());


        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.nex_video_view_sample_vast_wv);
        mVideoView = (NexVideoView)findViewById(R.id.video_view);
        mErrorTextView = (TextView)findViewById(R.id.error_text_view);

        mMediaController = new NexMediaController(this);
        mVideoView.setMediaController(mMediaController);

        mAdView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = mAdView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }

        mAdView.setWebChromeClient(new WebChromeClientCustomPoster());

        final NexPlayer nexplayer = mVideoView.getNexPlayer();

        mJSInterface = new NexVASTJavaScriptInterface(nexplayer, mAdView,this);
        mAdView.addJavascriptInterface(mJSInterface, "NexVASTPlayer");
        mJSInterface.setmMediaController(mMediaController);
        prepareVideoView();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_list_vast_wv_item));
        builder.setItems(NexAdsMetadata.getNameList(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String vastUrl = null;
                if(which == 0) {
                    showVASTUrlDialog();
                    return;
                }
                else {
                    vastUrl = NexAdsMetadata.getVASTUrl(which);
                    start(vastUrl, mCurrentPath);
                }
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                Log.d(LOG_TAG, "onCancel");
                finish();
            }
        });
        builder.create().show();

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(LOG_TAG, "onPause");
        if(!mJSInterface.isPlayAd()) {
            mJSInterface.pauseContent();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(LOG_TAG, "onResume");
        if (!mJSInterface.isPlayAd()) {
            mJSInterface.resumeContent();
        }
    }

    @Override
    protected void onDestroy() {
        Log.i(LOG_TAG, "onDestroy");
        PlayerEnginePreLoader.deleteAPKAsset(this);
        mVideoView.release();

        super.onDestroy();
    }


    // Override APIs for NexVASTPlayer.Listener
    @Override
    public void onTimeUpdate(int time) {
        final String cmd = "javascript:javaSetCurrentTime(" + time + ")";
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mAdView != null) {
                    mAdView.loadUrl(cmd);
                }
            }
        });
    }

    @Override
    public void onComplete() {
        mCompleteContent = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mAdView != null) {
                    mAdView.loadUrl("javascript:javaSetEndOfContent()");
                }
            }
        });

        if(mCompleteAd) {
            finish();
        }
    }

    // Override APIs for NexVASTJavaScriptInterface.Listener
    @Override
    public void onStartAd() {
        Log.d(LOG_TAG, "[VASTWebView onStartAd]");
        mCompleteAd = false;
        mJSInterface.pauseContent();
    }

    @Override
    public void onCompleteAd() {
        Log.d(LOG_TAG, "[VASTWebView onCompleteAd]");
        mCompleteAd = true;
        if(mCompleteContent) {
            finish();
        }
        mJSInterface.resumeContent();
    }

    @Override
    public void onPlayAd(boolean bPlay) {
        Log.d(LOG_TAG, "[VASTWebView onPlayAd]");
        mJSInterface.setPlayAd(bPlay);
    }

    private void preloadLibs() {
        if( !PlayerEnginePreLoader.isLoaded() ) {
            String libraryPath = this.getApplicationInfo().dataDir+"/" ;
            PlayerEnginePreLoader.Load(libraryPath, this, 3);
        }
    }

    public void prepareVideoView() {
        mVideoView.setOnPreparedListener(new NexVideoView.OnPreparedListener() {
            @Override
            public void onPrepared(NexPlayer mp) {
                Log.d(LOG_TAG, "[onPrepared]");
            }
        });

        mVideoView.setOnPauseCompleteListener(new NexVideoView.OnPauseCompleteListener() {
            @Override
            public void onPauseComplete(NexPlayer mp) {
                Log.d(LOG_TAG, "[onPauseComplete]");
            }
        });

        mVideoView.setOnResumeCompleteListener(new NexVideoView.OnResumeCompleteListener() {
            @Override
            public void onResumeComplete(NexPlayer mp) {
                Log.d(LOG_TAG, "[onResmeComplete]");

            }
        });

        mVideoView.setOnCompletionListener(new NexVideoView.OnCompletionListener() {
            @Override
            public void onCompletion(NexPlayer mp) {
                Log.d(LOG_TAG, "[onComplete]");
                onComplete();
            }
        });

        mVideoView.setOnTimeUpdateListener(new NexVideoView.OnTimeUpdateListener() {
            @Override
            public void onTime(NexPlayer mp, int currTime) {
                currTime = (int)(currTime/1000.0);
                onTimeUpdate(currTime);
            }
        });

        mVideoView.setOnSeekCompleteListener(new NexVideoView.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete(NexPlayer nexPlayer, int i, int i1) {
                Log.d(LOG_TAG, "[onSeekComplete] mIsPlayAd:" + mJSInterface.isPlayAd());
                if(mJSInterface.isPlayAd()) {
                    onPause();
                }
            }
        });
    }

    private void getIntentExtra(Intent intent) {
        Uri uri = intent.getData();

        if( uri != null ) {
            mCurrentUri = uri;
        } else {
            mLocalFileList = (ArrayList<File>) intent.getSerializableExtra("data");
            mCurrentIndex = intent.getIntExtra("selectedItem", 0);
            mCurrentPath = intent.getStringExtra("theSimpleUrl");

            if( mLocalFileList != null && mCurrentPath == null ) {
                mCurrentPath = mLocalFileList.get(mCurrentIndex).getAbsolutePath();
            }
        }
    }

    private void showVASTUrlDialog() {
        final ScrollView linearLayout = (ScrollView)View.inflate(this, R.layout.vast_url, null);

        AlertDialog.Builder alertDialogBuilder;
        alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle("VAST URL").setView(linearLayout);
        alertDialogBuilder.setPositiveButton(
                getResources().getString(R.string.play),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String url = setVastURL(linearLayout);
                        if (url != null) {
                            start(url, mCurrentPath);
                        } else {
                            Toast.makeText(getApplicationContext(), R.string.go_to_url_error, Toast.LENGTH_LONG).show();
                            start(null, mCurrentPath);
                        }
                    }
                }
        );

        alertDialogBuilder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                start(null, mCurrentPath);
            }
        });
        alertDialogBuilder.show();
    }

    private String setVastURL(ScrollView linearLayout) {
        EditText content = (EditText)linearLayout.findViewById(R.id.vast_url);
        String url = content.getText().toString();

        if(!content.getText().toString().equals(""))
            return url;

        return null;
    }

    private void start(String adUrl, String contentUrl) {
        if(adUrl != null) {
            final String encVastUrl;
            Uri indexUri = Uri.fromFile(new File("//android_asset/index.html"));

            final String indexURL = indexUri.toString();
            try {
                adUrl = URLEncoder.encode(adUrl, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                Log.e(LOG_TAG, "[onClick] Error : " + e.toString());
            } finally {
                encVastUrl = adUrl;
            }

            mAdView.loadUrl(indexURL);

            mAdView.setWebViewClient(new WebViewClient() {
                public void onPageFinished(WebView view, String url) {
                    Log.d(LOG_TAG, "[onPageFinished] URL : " + url);

                    if (url.equalsIgnoreCase(indexURL)) {
                        String setUrlCmd = "javascript:javaSetVASTUrl('" + encVastUrl + "')";
                        Log.d(LOG_TAG, "[onPageFinished] command : " + setUrlCmd);
                        view.loadUrl(setUrlCmd);
                        view.loadUrl("javascript:javaInit()");
                    }
                }

                @TargetApi(21)
                public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                    Log.d(LOG_TAG, "[shouldOverrideUrlLoading] URL : " + request.getUrl().toString());
                    if (request.getUrl().equals(Uri.parse(indexURL)) == false) {
                        Log.d(LOG_TAG, "[shouldOverrideUrlLoading]2 URL : " + request.getUrl().toString());
                        Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
                        mActivity.startActivity(intent);
                        return true;
                    }
                    return super.shouldOverrideUrlLoading(view, request);
                }

                public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                    Log.d(LOG_TAG, "[shouldOverrideKeyEvent] event : " + event.toString());

                    if (view.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                        Log.d(LOG_TAG, "[shouldOverrideKeyEvent] goBack");
                        view.goBack();
                        return true;
                    }

                    return super.shouldOverrideKeyEvent(view, event);
                }
            });
        }

        mCompleteContent = false;
        mVideoView.setVideoURI(Uri.parse(contentUrl));
        if(adUrl == null) {
            mAdView.setVisibility(View.GONE);
            mJSInterface.resumeContent();
        }
    }
}
