package com.xixun.xixunplayer;

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

import java.text.DecimalFormat;
import java.util.ArrayList;

import gnph.util.JSMap;
import gnph.util.NumFmts;
import gnph.util.Txts;
import gnph.util.URLConn;

public class SrcSensor extends WebView implements IntentReceiver, Choreographer.FrameCallback {

    static String directs[] = {"NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N"};
    MainActivity act;
    ArrayList<String> htmls;
    String prefix, url, text;
    int interval, pageDur, cur;

    @SuppressLint("SetJavaScriptEnabled")
    public SrcSensor(Prog prog, JSMap json, int width, int height) {
        super(prog.getContext());
        act = (MainActivity) prog.getContext();
        setBackgroundColor(Color.TRANSPARENT);
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        setInitialScale(100);
        getSettings().setJavaScriptEnabled(true);

        var html = json.stnn("html").replace("%Co2", "%CO2").trim();
        htmls = Txts.split(html, "</p>", 1);
        pageDur = json.intg("speed")*1000;
        if(pageDur==0) pageDur = json.intg("timeSpan")*1000 / htmls.size();
        url = json.str("sUrl");
        interval = json.intg("sInterval") * 1000;
        if(url!=null && interval>0 && html.contains("%s")) {
            nextMs = System.currentTimeMillis() + interval;
            Util.println("url: "+url);
            try {
                text = URLConn.send(url);
            } catch (Exception e) {
                text = "";
                Util.printStackTrace(e);
            }
        }
        prefix = "<body style=\"color:#fff; margin:0;padding:0;";
        var lineHeight = json.str("lineHeight");
        if(lineHeight!=null) prefix += "line-height:"+lineHeight+";";
        var backgroundColor = json.str("backgroundColor");
        if(backgroundColor!=null) prefix += "background-color:"+backgroundColor+";";
        if(json.bool("center")) prefix += "display:flex; align-items:center;";
        prefix += "\">";
        prog.calls.add(this);
    }

    static DecimalFormat fmt0 = NumFmts.newDecFmt("0");
    public void onReceive(Intent intent) {
        try {
            var htm = htmls.get(cur);
            var temp = intent.getFloatExtra("temperature", -99f);
            var fa = temp * 1.8f + 32;
            var noTemp = temp==-99f;
            var t2 = noTemp ? "--" : NumFmts.fix2().format(temp);
            var t1 = noTemp ? "--" : NumFmts.fix1().format(temp);
            var tn = noTemp ? "--" : String.valueOf(temp);
            var t0 = noTemp ? "--" : fmt0.format(temp);
            var f2 = noTemp ? "--" : NumFmts.fix2().format(fa);
            var f1 = noTemp ? "--" : NumFmts.fix1().format(fa);
            var fn = noTemp ? "--" : String.valueOf(fa);
            var f0 = noTemp ? "--" : fmt0.format(fa);

            var humi = intent.getFloatExtra("humidity", -1);
            var h = humi == -1 ? "--" : String.valueOf(humi);
            var noise = intent.getFloatExtra("noise", -1);
            var windSpeed = intent.getFloatExtra("windSpeed", -1);
            int pm2 = intent.getIntExtra("pm2.5", -1);
            int pm10 = intent.getIntExtra("pm10", -1);
            int windDir = intent.getIntExtra("windDirection", -1);
            int SO2 = intent.getIntExtra("SO2", -1);
            int NO2 = intent.getIntExtra("NO2", -1);
            int CO2 = intent.getIntExtra("CO2", -1);
            int CO = intent.getIntExtra("CO", -1);
            int O3 = intent.getIntExtra("O3", -1);
            var pressure = intent.getFloatExtra("pressure", -1);
            var rainfall = intent.getFloatExtra("rainfall", -1);
            int radiation = intent.getIntExtra("radiation", -1);
            int beam = intent.getIntExtra("beam", -1);
            //int brightness = intent.getIntExtra("brightness", -1);
            var dp = intent.getFloatExtra("dpTemperature", -99f);

            if(text!=null) htm = htm.replace("%s", text);
            htm = htm.replace("%T2", t2 + '℃').replace("%T1", t1 + '℃').replace("%T", tn + '℃').replace("%c2", t2).replace("%c1", t1).replace("%c", t0)
                    .replace("%t2", f2 + '℉').replace("%t1", f1 + '℉').replace("%t", fn + '℉').replace("%f2", f2).replace("%f1", f1).replace("%f", f0)
                    .replace("%RH", h+'%').replace("%h", h)
                    .replace("%ns", (noise == -1 ? "--" : String.valueOf(noise)) + "dB")
                    .replace("%ws", (windSpeed == -1 ? "--" : String.valueOf(windSpeed)) + "m/s")
                    .replace("%wd", windDir<0||windDir>=directs.length ? "--" : directs[windDir])
                    .replace("%pm2", (pm2 == -1 ? "--" : String.valueOf(pm2)) + "μg/m³")
                    .replace("%pm10", (pm10 == -1 ? "--" : String.valueOf(pm10)) + "μg/m³")

                    .replace("%SO2", (SO2 == -1 ? "--" : String.valueOf(SO2)) +"ppb")
                    .replace("%NO2", (NO2 == -1 ? "--" : String.valueOf(NO2)) +"ppb")
                    .replace("%CO2", (CO2 == -1 ? "--" : String.valueOf(CO2)) +"ppm")
                    .replace("%CO", (CO == -1 ? "--" : String.valueOf(CO)) +"ppb")
                    .replace("%O3", (O3 == -1 ? "--" : String.valueOf(O3)) +"ppb")
                    .replace("%dp", (dp == -1 ? "--" : String.valueOf(dp)) +'℃')
                    .replace("%pressure", (pressure == -1 ? "--" : String.valueOf(pressure))+"hPa")
                    .replace("%rainfall", (rainfall == -1 ? "--" : String.valueOf(rainfall))+"mm")
                    .replace("%radiation", (radiation == -1 ? "--" : String.valueOf(radiation))+"W/m²")
                    .replace("%bm", (beam == -1 ? "--" : String.valueOf(beam))+"lux");

            loadDataWithBaseURL(null, prefix+htm+"</p></body>", "text/html", "UTF-8", null);
        } catch (Exception e) {
            Util.printStackTrace(e);
        }
    }

    long nextPageMs, nextMs;
    boolean isFirst = true;

    @Override
    public void doFrame(long ms) {
        if(! isShown()) {
            if(! isFirst) {
                act.environs.remove(this);
                isFirst = true;
            }
            return;
        }
        boolean needRefresh = false;
        if(isFirst) {
            isFirst = false;
            cur = 0;
            nextPageMs = ms + pageDur;
            act.environs.add(this);
            needRefresh = true;
        } else if(ms>=nextPageMs) {
            nextPageMs += pageDur;
            if(cur>=htmls.size()-1) cur = 0;
            else cur++;
            needRefresh = true;
        }
        if(text!=null && ms>=nextMs) {
            nextMs = ms + interval;
            try {
                text = URLConn.send(url);
                needRefresh = true;
            } catch (Exception e) {
                Util.printStackTrace(e);
            }
        }
        if(needRefresh) onReceive(act.environIntent);
    }
}
