package com.sheep.gamegroup.util.viewHelper;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;

/**
 * Created by realicing on 2018/11/13.
 * realicing@sina.com
 */
public class WebViewVideoHelper {
    private WebView webView;
    private Activity activity;


    /**
     * 视频全屏参数
     */
    protected final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;

    public void init(Activity activity, WebView webView) {
        this.activity = activity;
        this.webView = webView;
        initWebView();
        CommonUtil.getInstance().setDownloadListener(ActivityManager.getInstance().currentActivity(), webView);
    }

    public void initWebView() {
        WebSettings webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSetting.setSupportZoom(true);
//        webSetting.setBuiltInZoomControls(true);
//        webSetting.setUseWideViewPort(true);
        //下面这行会影响setDownloadListener，暂时注释掉，等有空研究一下
//        webSetting.setSupportMultipleWindows(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);


        webSetting.setCacheMode(android.webkit.WebSettings.LOAD_DEFAULT);
        webSetting.setLoadWithOverviewMode(true);
        activity.getWindow().setFormat(PixelFormat.TRANSLUCENT);
        webView.setWebChromeClient(new WebChromeClient() {

            /**视频播放相关的方法*
             *
             */


            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(SheepApp.getInstance());
                frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                super.onShowCustomView(view, callback);
                showCustomView(view, callback);
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//设置横屏
            }

            @Override
            public void onHideCustomView() {
                hideCustomView();
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置竖屏
                super.onHideCustomView();
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.println(getClass().getSimpleName(), "shouldOverrideUrlLoading", url);
                //Android8.0以下的需要返回true 并且需要loadUrl；8.0之后效果相反
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    return false;
                }
                webView.loadUrl(url);
                return true;
            }
        });
    }

    /**
     * 视频播放全屏
     */

    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        activity.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) activity.getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(activity);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }


    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        activity.getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Log.i("bar------", visible + "");
    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) activity.getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        webView.setVisibility(View.VISIBLE);
    }

    public void onBackUp() {
/**回退键 事件处理 优先级:
 视频播放全屏 - 网页回退 - 关闭页面*/
        if (customView != null) {
            hideCustomView();
        } else if (webView != null && webView.canGoBack()) {
            webView.goBack();
        } else {
            activity.finish();
        }
    }

    public boolean onBackPressed() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }
    public void onResume(){
        try {
            if (webView != null) {
//                webView.resumeTimers();
                webView.onResume();
                webView.getClass().getMethod("onResume").invoke(webView, (Object[]) null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void onPause() {
        if (webView != null) {
            webView.onPause();
            //            webView.pauseTimers();
            try {
                webView.getClass().getMethod("onPause").invoke(webView, (Object[]) null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public void onDestroy() {
        if (webView != null) {
//            webView.onPause();
//            webView.freeMemory();
//            webView.removeAllViews();
            webView.destroy();
//            webView = null;
        }
    }

    /**
     * 全屏容器界面
     */


    class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            switch (evt.getAction()) {
                case MotionEvent.ACTION_POINTER_UP:
                    break;
            }
            return true;
        }
    }

}
