package com.xixun.xixunplayer;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.net.http.SslError;
import android.view.Choreographer;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import gnph.util.JSMap;

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

    String url;
    int refresh;

    @SuppressLint("SetJavaScriptEnabled")
    public SrcWeb(Prog prog, JSMap json) {
        super(prog.getContext());
        var settings = getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setLoadsImagesAutomatically(true);
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        setBackgroundColor(Color.TRANSPARENT);
        setInitialScale(json.intg("zoom", 100));
        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")+")");
            }
        });
        loadUrl(url = json.str("url"));
        refresh = json.intg("refreshSec")*1000;
        if(refresh>0 && url!=null) prog.calls.add(this);
        nextMs = System.currentTimeMillis() + refresh;
    }

    long nextMs;

    @Override
    public void doFrame(long ms) {
        if(! isShown()) return;
        if(ms>=nextMs) {
            nextMs = ms + refresh;
            loadUrl(url);
        }
    }
}
