package jp.odakyu.toiletsignage.connection;

import android.util.Base64;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by agentec on 2018/01/23.
 */

public class NtpServerConnection {
    private static final String NTP_SERVER_URL = "http://ntp-a1.nict.go.jp/cgi-bin/ntp";
    private static final int CONNECTION_TIMEOUT = 5 * 1000;
    private static final int READ_TIMEOUT = 5 * 1000;

    public static String connectionNtpServer() throws IOException {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(NTP_SERVER_URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setRequestMethod("GET");
            conn.connect();
            int statusCode = conn.getResponseCode();

            if (statusCode == HttpURLConnection.HTTP_OK) {
                StringBuffer result = new StringBuffer();
                //responseの読み込み
                final InputStream in = conn.getInputStream();
                String encoding = conn.getContentEncoding();
                if (null == encoding) {
                    encoding = "UTF-8";
                }
                final InputStreamReader inReader = new InputStreamReader(in, encoding);
                final BufferedReader bufferedReader = new BufferedReader(inReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    if (line.indexOf("<") == -1 && line.indexOf(">") == -1) {
                        result.append(line);
                    }
                }
                bufferedReader.close();
                inReader.close();
                in.close();

                return result.toString();
            }
            return null;

        } catch(IOException e) {
            throw e;
        } finally {
            if(conn != null) {
                conn.disconnect();
            }
        }
    }

}
