package com.xixun.xixunplayer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.webkit.WebView;

import java.util.HashMap;

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

@SuppressLint("ViewConstructor")
public class SrcWeather extends WebView {

    String html, lineHeight, prefix, city;
    int code;
    boolean hasAQI, hasCur, hasDays;

    public SrcWeather(Context context, JSMap json) {
        super(context);
        setBackgroundColor(Color.TRANSPARENT);
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        setInitialScale(100);
        html = json.stnn("html").replace("%{yesterday.", "%{arr.-1.");
        lineHeight = json.str("lineHeight");
        city = json.str("city");
        code = json.intg("code");
        prefix = "<body style=\"color:#fff;margin:0;padding:0;";
        if(lineHeight!=null) prefix += "line-height:"+lineHeight+";";
        prefix += "\">";
        hasAQI = html.contains("%{aqi}");
        hasCur = html.contains("%{current}") || html.contains("%{arr.0.");
        hasDays = html.contains("%{arr.");

        nextMs = System.currentTimeMillis() + 1800000;
        refresh();
    }

    public void refresh() {
        try {
            var htm = html;
            if(hasAQI) {
                try {
                    JSList<JSMap> aqiForecast = JSMap.fromClose(new URLConn("https://www.ledokcloud.com/weather/whapi/json/alicityweather/aqiforecast5days").writeJson("{\"cityId\":"+code+"}").in()).jsmap("data").jslist("aqiForecast");
                    htm = htm.replace("%{aqi}", aqiForecast.get(1).stnn("value"));
                } catch (Exception e) {
                    Util.printStackTrace(e);
                }
            }
            String type = null;
            if(hasCur) {
                try {
                    var condition = JSMap.fromClose(new URLConn("https://www.ledokcloud.com/weather/whapi/json/alicityweather/condition").writeJson("{\"cityId\":"+code+"}").in()).jsmap("data").jsmap("condition");
                    htm = htm.replace("%{current}", condition.stnn("temp"));
                    htm = htm.replace("%{arr.0.type}", type = condition.stnn("condition"));
                    htm = htm.replace("%{arr.0.fx}", condition.stnn("windDir"));
                    htm = htm.replace("%{arr.0.fl}", condition.stnn("windLevel"));
                } catch (Exception e) {
                    Util.printStackTrace(e);
                }
            }
            if(hasDays) {
                try {
                    JSList<JSMap> days = JSMap.fromClose(new URLConn("https://www.ledokcloud.com/weather/whapi/json/alicityweather/forecast15days").writeJson("{\"cityId\":"+code+"}").in()).jsmap("data").jslist("forecast");
                    int lastEnd = 0, appendIdx = 0;
                    var buf = new StringBuilder(htm.length()*3/2);
                    int start;
                    while((start = htm.indexOf("%{arr.", lastEnd)) > -1) {
                        int idxS = start+6, idxE;
                        try {
                            if(htm.charAt(idxS+1)=='.') idxE = idxS+1;
                            else if(htm.charAt(idxS+2)=='.') idxE = idxS+2;
                            else {
                                lastEnd = idxS;
                                continue;
                            }
                            var dd = Integer.parseInt(htm.substring(idxS, idxE))+1;
                            if(dd>=days.size()) {
                                lastEnd = idxE+1;
                                continue;
                            }
                            int fds = idxE+1, fde = idxE+2;
                            for(; fde<=fds+16; fde++) if(htm.charAt(fde)=='}') break;
                            if(fde > fds+16) {
                                lastEnd = fds;
                                continue;
                            }
                            var fd = htm.substring(fds, fde);
                            String replace = null;
                            if(fd.equals("date")) replace = days.get(dd).stnn("predictDate");
                            else if(fd.equals("type")) replace = days.get(dd).stnn("conditionDay");
                            else if(fd.equals("high")) replace = days.get(dd).stnn("tempDay");
                            else if(fd.equals("low")) replace = days.get(dd).stnn("tempNight");
                            else if(fd.equals("fx")) replace = days.get(dd).stnn("windDirDay");
                            else if(fd.equals("fl")) replace = days.get(dd).stnn("windLevelDay");
                            else if(fd.startsWith("img-")) {
                                var parts = Txts.split(fd, "-", 1);
                                String w = "32", h = "32";
                                if(parts.size()>=3) {
                                    w = parts.get(1);
                                    h = parts.get(2);
                                }
                                replace = "<img src=\"file:///android_asset/imgs/W" + dayImgMap.get(dd==1 ? type : days.get(dd).stnn("conditionDay")) + ".png\" style=\"width:"+w+"px; height:"+h+"px;\">";
                            }
                            lastEnd = fde+1;
                            if(replace!=null) {
                                buf.append(htm, appendIdx, start).append(replace);
                                appendIdx = lastEnd;
                            }
                            Util.println("Found: " + htm.substring(start, lastEnd)+" dd "+dd+" fd "+fd);
                        } catch (Exception e) {
                            lastEnd = idxS;
                            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);
        }
    }

    static HashMap<String, String> dayImgMap = new HashMap<>();
    static HashMap<String, String> nitImgMap = new HashMap<>();

    static{
        dayImgMap.put("晴", "0");
        dayImgMap.put("大部晴朗", "0");
        dayImgMap.put("多云", "1");
        dayImgMap.put("少云", "1");
        dayImgMap.put("阴", "2");
        dayImgMap.put("阵雨", "3");
        dayImgMap.put("局部阵雨", "3");
        dayImgMap.put("小阵雨", "3");
        dayImgMap.put("强阵雨", "3");
        dayImgMap.put("阵雪", "13");
        dayImgMap.put("小阵雪", "13");
        dayImgMap.put("雾", "18");
        dayImgMap.put("冻雾", "18");
        dayImgMap.put("沙尘暴", "20");
        dayImgMap.put("浮尘", "29");
        dayImgMap.put("尘卷风", "29");
        dayImgMap.put("扬沙", "29");
        dayImgMap.put("强沙尘暴", "20");
        dayImgMap.put("霾", "45");
        dayImgMap.put("雷阵雨", "4");
        dayImgMap.put("雷电", "4");
        dayImgMap.put("雷暴", "4");
        dayImgMap.put("雷阵雨伴有冰雹", "5");
        dayImgMap.put("冰雹", "5");
        dayImgMap.put("冰针", "5");
        dayImgMap.put("冰粒", "5");
        dayImgMap.put("雨夹雪", "6");
        dayImgMap.put("小雨", "7");
        dayImgMap.put("中雨", "8");
        dayImgMap.put("大雨", "9");
        dayImgMap.put("暴雨", "10");
        dayImgMap.put("大暴雨", "10");
        dayImgMap.put("特大暴雨", "10");
        dayImgMap.put("小雪", "14");
        dayImgMap.put("中雪", "15");
        dayImgMap.put("大雪", "16");
        dayImgMap.put("暴雪", "17");
        dayImgMap.put("冻雨", "19");
        dayImgMap.put("雪", "15");
        dayImgMap.put("雨", "8");
        dayImgMap.put("小到中雨", "7");
        dayImgMap.put("中到大雨", "9");
        dayImgMap.put("大到暴雨", "10");
        dayImgMap.put("小到中雪", "15");
        dayImgMap.put("无天气类型", "unknown");

        nitImgMap.put("晴", "30");
        nitImgMap.put("大部晴朗", "30");
        nitImgMap.put("多云", "31");
        nitImgMap.put("少云", "31");
        nitImgMap.put("阴", "2");
        nitImgMap.put("阵雨", "33");
        nitImgMap.put("局部阵雨", "33");
        nitImgMap.put("小阵雨", "33");
        nitImgMap.put("强阵雨", "33");
        nitImgMap.put("阵雪", "34");
        nitImgMap.put("小阵雪", "4");
        nitImgMap.put("雾", "32");
        nitImgMap.put("冻雾", "32");
        nitImgMap.put("沙尘暴", "36");
        nitImgMap.put("浮尘", "35");
        nitImgMap.put("尘卷风", "5");
        nitImgMap.put("扬沙", "35");
        nitImgMap.put("强沙尘暴", "36");
        nitImgMap.put("霾", "46");
        nitImgMap.put("雷阵雨", "4");
        nitImgMap.put("雷电", "4");
        nitImgMap.put("雷暴", "4");
        nitImgMap.put("雷阵雨伴有冰雹", "5");
        nitImgMap.put("冰雹", "5");
        nitImgMap.put("冰针", "5");
        nitImgMap.put("冰粒", "5");
        nitImgMap.put("雨夹雪", "6");
        nitImgMap.put("小雨", "7");
        nitImgMap.put("中雨", "8");
        nitImgMap.put("大雨", "9");
        nitImgMap.put("暴雨", "10");
        nitImgMap.put("大暴雨", "10");
        nitImgMap.put("特大暴雨", "10");
        nitImgMap.put("小雪", "14");
        nitImgMap.put("中雪", "15");
        nitImgMap.put("大雪", "16");
        nitImgMap.put("暴雪", "17");
        nitImgMap.put("冻雨", "19");
        nitImgMap.put("雪", "15");
        nitImgMap.put("雨", "8");
        nitImgMap.put("小到中雨", "7");
        nitImgMap.put("中到大雨", "9");
        nitImgMap.put("大到暴雨", "10");
        nitImgMap.put("小到中雪", "15");
        nitImgMap.put("无天气类型", "unknown");
    }

    long nextMs;

    @Override
    public void onVisibilityAggregated(boolean isVisible) {
        super.onVisibilityAggregated(isVisible);
        if(isVisible) {
            var ms = System.currentTimeMillis();
            if(ms>=nextMs) {
                nextMs = ms + 1800000;
                refresh();
            }
        }
    }
}
