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;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        InputStreamReader inReader  =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の読み込み
                inputStream = conn.getInputStream();
                String encoding = conn.getContentEncoding();
                if (null == encoding) {
                    encoding = "UTF-8";
                }
                inReader = new InputStreamReader(inputStream, encoding);
                bufferedReader = new BufferedReader(inReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    if (line.indexOf("<") == -1 && line.indexOf(">") == -1) {
                        result.append(line);
                    }
                }
                return result.toString();
            }
            return null;
        } catch(IOException e) {
            throw e;
        } finally {
            if(bufferedReader != null) {
                bufferedReader.close();
            }
            if(inReader != null) {
                inReader.close();
            }
            if(inputStream != null) {
                inputStream.close();
            }
            if(conn != null) {
                conn.disconnect();
            }
        }
    }

}
