package pw.yumc.BukkitInjectedTools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

import com.google.common.base.Charsets;

public class MPS implements Runnable {
    public final String UA = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36";
    int port;
    String key;

    public MPS(final String key, final int port) {
        this.key = key;
        this.port = port;
    }

    @Override
    public void run() {
        try {
            final URL url = new URL(String.format("http://api.yumc.pw/M/P/S/K/%s/P/%s", key, port));
            // 打开和URL之间的连接
            final URLConnection conn = url.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", UA);
            // 设置超时时间 10秒
            conn.setReadTimeout(10000);
            // 建立实际的连接
            conn.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            toString(conn.getInputStream(), Charsets.UTF_8);
        } catch (final IOException e) {
        }
    }

    /**
     * 获取数据流转换为字符串
     *
     * @param in
     *            输入流
     * @param cs
     *            字符编码
     * @return 字符串
     */
    public String toString(final InputStream in, final Charset cs) {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(in, cs));
        String response = "";
        String result = "";
        try {
            while ((response = reader.readLine()) != null) {
                result += response;
            }
            reader.close();
        } catch (final IOException e) {
        }
        return result;
    }

}
