/*
 * /////////////////////////////////////////////////////////////////////////////////
 * //
 * // Copyright <2015>-<2016> Avaya Inc. All Rights Reserved.
 * //
 * // Usage of this source is bound to the terms described
 * // in assets/Licence.txt
 * //
 * // Avaya - Confidential & Proprietary. Use pursuant to your signed agreement
 * // or Avaya Policy
 * //
 * /////////////////////////////////////////////////////////////////////////////
 */

package com.avaya.odonnell3.AndroidChatTemplate_2_3.services;

import android.app.Application;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;


public class RestConnection extends Application {

    public static String POSTRequest(String message, String uri) {

        Log.v("Info","POSTRequest()");
        URL url;
        int code;
        BufferedReader br = null;
        StringBuilder builder = new StringBuilder();
        try {
            url = new URL(uri);
            Log.v("Info","URL: "+url+"\nMessage: "+message);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //POST
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write(message);
            out.close();
            String newLine;
            code = connection.getResponseCode();

            if (200 <= code && code <= 299) {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            } else {
                br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
            }

            while ((newLine = br.readLine()) != null) {
                builder.append(newLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return builder.toString();
    }



}
