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 2017/12/11.
 */

public class ToiletServerConnection {
    private static final String TOILET_INFO_URL = "https://odakyu.api.toilet.mono-connect.jp/1/placements/%d/box_summaries_search";
    private static final String LOGIN_ID = "nh2h2KntNPpgXcqEAtcJxwJd49jNcJ4J";
    private static final String PASSWORD = "jm2kCd6ZK2EZTzcMgxtge3AC4EeJ4ZqW";
    private static final int CONNECTION_TIMEOUT = 5 * 1000;
    private static final int READ_TIMEOUT = 5 * 1000;

    public static String connectionToiletServer(int toiletId) throws IOException {
        URL url = new URL(String.format(TOILET_INFO_URL, toiletId));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((LOGIN_ID + ":" + PASSWORD).getBytes(), Base64.NO_WRAP));
        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) {
                result.append(line);
            }
            bufferedReader.close();
            inReader.close();
            in.close();

            return result.toString();
        }
        return null;
    }

}
