package jp.odakyu.toiletsignage.connection;

import android.util.Base64;

import java.io.BufferedReader;
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 final String TOILET_INFO_URL = "https://odakyu.api.toilet.mono-connect.jp/1/placements/%d/box_summaries_search ";
    private final String LOGIN_ID = "nh2h2KntNPpgXcqEAtcJxwJd49jNcJ4J";
    private final String PASSWORD = "jm2kCd6ZK2EZTzcMgxtge3AC4EeJ4ZqW";
    private final int CONNECTION_TIMEOUT = 30 * 1000;
    private final int READ_TIMEOUT = 30 * 1000;

    public String connectionToiletServer(int toiletId) throws  Exception {
        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 = null;
            while((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            bufferedReader.close();
            inReader.close();
            in.close();

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

}
