package it.unipr.mobdev.youtube.remote;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

public class RESTRequestExecutor {

	public static final String execute(RESTRequest request)
			throws RESTServiceException {
		String value = null;
		try {
			value = RESTRequestExecutor.restCall(request);
			return value;
		} catch (RESTServiceException e) {
			throw e;
		}
	}

	private static String restCall(RESTRequest request)
			throws RESTServiceException {
		//String desiredUrl = request.requestURL();
		//URL url = null;
		BufferedReader reader = null;
		StringBuilder stringBuilder;
		try {
			
			HttpURLConnection connection = request.getURLConnection();
			
			if(connection.getRequestMethod().equals("POST"))
			{
				
				connection.setDoInput(true);
				connection.setDoOutput(true);
				
				DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
				outStream.writeBytes(request.getPOSTBody());
		        outStream.flush();
		        outStream.close();
			}
			else
			{
				connection.connect();
			}
			
			// read the output from the server
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			stringBuilder = new StringBuilder();
			
			String line = null;
			
			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line + "\n");
			}
			
			return stringBuilder.toString();
			
		} catch (Exception e) {
			// e.printStackTrace();
			throw new RESTServiceException(request, e.getLocalizedMessage());
		} finally {
			// close the reader; this can throw an exception too, so
			// wrap it in another try/catch block.
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException ioe) {
					// ioe.printStackTrace();
					throw new RESTServiceException(request,
							ioe.getLocalizedMessage());
				}
			}
		}
	}

}
