package com.xixun.xixunplayer;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.view.Choreographer;
import android.webkit.WebView;

import gnph.util.JSMap;
import gnph.util.URLConn;

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

    String html, lineHeight, prefix, url;

    public SrcVisitor(Prog prog, JSMap json) {
        super(prog.getContext());
        setBackgroundColor(Color.TRANSPARENT);
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        setInitialScale(100);
        html = json.stnn("html").replace("%{yesterday.", "%{arr.-1.");
        lineHeight = json.str("lineHeight");
        url = json.str("url");
        prefix = "<body style=\"color:#fff;margin:0;padding:0;";
        if(lineHeight!=null) prefix += "line-height:"+lineHeight+";";
        prefix += "\">";
        if(url!=null) prog.calls.add(this);
    }

    public void refresh() {
        try {
            var htm = html;
                try {
                var res = JSMap.fromClose(new URLConn(url).in()).jsmap("data");
                int lastEnd = 0, appendIdx = 0;
                var buf = new StringBuilder(htm.length()*3/2);
                int start;
                while((start = htm.indexOf("%{", lastEnd)) > -1) {
                    int fds = start+2, fde = start+2;
                    try {
                        for(; fde<=fds+16; fde++) if(htm.charAt(fde)=='}') break;
                        if(fde > fds+16) {
                            lastEnd = fds;
                            continue;
                        }
                        lastEnd = fde+1;
                        if(fde == fds) continue;
                        var fd = htm.substring(fds, fde);
                        var replace = res.str(fd);
                        if(replace!=null) {
                            buf.append(htm, appendIdx, start).append(replace);
                            appendIdx = lastEnd;
                        }
                        Util.println("Found: " + htm.substring(start, lastEnd)+" fd "+fd);
                    } catch (Exception e) {
                        lastEnd = fds;
                        Util.printStackTrace(e);
                    }
                }
                if(buf.length()>0) {
                    if(appendIdx < htm.length()) buf.append(htm, appendIdx, htm.length());
                    htm = buf.toString();
                }
            } catch (Exception e) {
                Util.printStackTrace(e);
            }
            loadDataWithBaseURL(null, prefix+htm+"</body>", "text/html", "UTF-8", null);
        } catch (Exception e) {
            Util.printStackTrace(e);
        }
    }

    long nextMs;

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