package cn.com.tenlion.bigdata.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WeatherUtil {

    private final static String  url = "https://api.seniverse.com/v3/weather/now.json";

    private final static ConcurrentHashMap<String, Map<String, Object>> weather = new ConcurrentHashMap();

    public final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyyMMddHH");

    public static Map<String, Object> getWeather(String id) throws Exception {
        String date = sdfTime.format(new Date());
        if (weather.get(id + "_" + date) != null) {
            return weather.get(id + "_" + date);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("key", "Sk1Gt66B1Z-ZsEJP5");
        params.put("location", id);
        params.put("language", "zh-Hans");
        params.put("unit", "c");
        String result = HttpUtil.doGet(url, params);
        System.out.println("天气预报返回 : " + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray array = jsonObject.getJSONArray("results");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if(array.size() > 0) {
            JSONObject object = array.getJSONObject(0).getJSONObject("now");
            JSONObject location = array.getJSONObject(0).getJSONObject("location");
            String text = object.getString("text");
            String temperature = object.getString("temperature");
            String code = object.getString("code");
            resultMap.put("text", text);
            resultMap.put("temperature", temperature);
            resultMap.put("code", code);
            resultMap.put("city", location.getString("name"));
            weather.put(id + "_" + date, resultMap);
            System.out.println(resultMap.toString());
        }
        return resultMap;
    }

    public static void main(String[] args) throws Exception {
        WeatherUtil.getWeather("WRR2Q2Z7CXWM");
    }

}
