package com.xixun.xixunplayer;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Build;
import android.view.Choreographer;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.ArrayList;

import gnph.util.JSMap;

@SuppressLint("ViewConstructor")
public class SrcWeb extends WebView implements Choreographer.FrameCallback {

    String url;
    int refresh;
    ArrayList<Choreographer.FrameCallback> calls;

    @SuppressLint("SetJavaScriptEnabled")
    public SrcWeb(Prog prog, String url, JSMap json) {
        super(prog.getContext());
        this.url = url;
        var settings = getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setLoadsImagesAutomatically(true);
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        setBackgroundColor(Color.TRANSPARENT);
        setInitialScale(json.intg("zoom", 100));
        clearCache(true);
        setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed(); //忽略SSL证书错误，加载网页
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                view.loadUrl("javascript:window.scrollTo("+json.str("offX", "0")+", "+json.str("offY", "0")+")");
            }
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if(request.isForMainFrame() && error.getErrorCode()==-2 && request.getUrl().toString().equals(url)) needReload = true;
                    Util.println("  WebView ReceivedError "+error.getErrorCode()+" "+error.getDescription()+"; isForMainFrame "+request.isForMainFrame()+" URL "+request.getUrl());
                }
            }
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                Util.println("  WebView ReceivedHttpError "+errorResponse.getStatusCode()+"; isForMainFrame "+request.isForMainFrame()+" URL "+request.getUrl());
            }
        });
        loadUrl(url);
        refresh = json.intg("refreshSec")*1000;
        if(refresh==0 || Util.custom!=Util.Custom.Yishi) this.calls = prog.calls;
        prog.calls.add(this);
        nextMs = System.currentTimeMillis() + refresh;
    }

    long nextMs;
    int cnt, w, h;
    boolean needReload;
    @Override
    public void doFrame(long ms) {
        if(! isShown()) return;

        if(Util.custom==Util.Custom.Yishi) {
            if(refresh > 0) {
                if(ms>=nextMs) {
                    nextMs = ms + refresh;
                    loadUrl(url);
                }
            } else if(++cnt>=600) {
                cnt = 0;
                if(needReload) {
                    needReload = false;
                    loadUrl(url);
                    Util.println("  WebView Refreshed");
                }
            }
            if(Util.screenWidth!=w || Util.screenHeight!=h) {
                w = Util.screenWidth;
                h = Util.screenHeight;
                Util.println("  w "+w+" h "+h);
                setLayoutParams(new AbsLayout.LayoutParams(0, 0, w, h));
            }
        } else {
            if(refresh > 0) {
                if(ms>=nextMs) {
                    nextMs = ms + refresh;
                    loadUrl(url);
                }
            } else if(++cnt>=600) {
                cnt = 0;
                if(needReload) {
                    needReload = false;
                    loadUrl(url);
                    Util.println("  WebView Refreshed");
                } else if(calls!=null) {
                    calls.remove(this);
                    calls = null;
                }
            }
        }
    }
}
