package com.diaoyun.zion.chinafrica.bis.impl;

import com.diaoyun.zion.master.util.HttpClientUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;

/**
 * 网络接口调用
 *
 * @author G
 */
public class NetWorkSpider {

    /**
     * 调用和讯网上的汇率接口 http://webforex.hermes.hexun.com/forex/quotelist?code=FOREXUSDX,
     *
     * FOREXUSDCNY,FOREXEURUSD,FOREXUSDJPY,FOREXGBPUSD,FOREXUSDCAD,FOREXUSDCHF,
     * FOREXAUDUSD,FOREXGBPJPY,FOREXXAUUSD&column=Price,Code,Name,UpdownRate,PriceWeight'
     */
    private static final String exchangeRateUrl = "http://webforex.hermes.hexun.com/forex/quotelist?";

    /**
     * 从和讯网获取汇率
     * @param  code 暂支持单个币种传入，后续可以增加
     * @return
     */
    public static BigDecimal getRateFromHexun(String code) throws IOException, URISyntaxException {
        String apiUrl=exchangeRateUrl+"code="+code+"&column=Price,Code,Name,UpdownRate,PriceWeight";
        String dataUrl=HttpClientUtil.getContentByUrl(apiUrl,"");
        int firstBrackets=dataUrl.indexOf("(");
        int lastBrackets=dataUrl.lastIndexOf(")");
        String jsonStr=dataUrl.substring(firstBrackets+1,lastBrackets);
        JsonObject rateJson = new JsonParser().parse(jsonStr).getAsJsonObject();
        JsonArray dataArray0= rateJson.getAsJsonArray("Data");
        JsonArray dataArray1= (JsonArray) dataArray0.get(0);
        JsonArray dataArray2= (JsonArray) dataArray1.get(0);
        int price=dataArray2.get(0).getAsInt();
        int priceWeight=dataArray2.get(4).getAsInt();
        BigDecimal priceDecimal = BigDecimal.valueOf(price);
        BigDecimal weightDecimal = BigDecimal.valueOf(priceWeight);
        return priceDecimal.divide(weightDecimal);
    }

}
