package base.connection;

import libcloud.providers.ibm.IBMDriver;
import libcloud.providers.ibm.IBMHandler;
import base.interfaces.IResponse;

/**
 * Default handler for request responses.  Subclasses should override 
 * these methods for custom handling.
 */
public class ResponseHandler {
	
	protected IResponse response;
	
	protected Object object;

	/**
	 * Constructs the handler with the given response.
	 * 
	 * @param response is the request's response
	 */
	public ResponseHandler(IResponse response) {
		this.response = response;
		
		if (success()) {
			parseBody();
		} else {
			throw new RuntimeException(parseError());
		}
	}
	
	/**
	 * Returns the response's processed representation.
	 * 
	 * @return Object is the response's parsed object for additional processing
	 */
	public Object getParsedObject() {
		return object;
	}
	
	/**
	 * Returns the original response.
	 * 
	 * @return IResponse is the request's original response
	 */
	public IResponse getResponse() {
		return response;
	}
	
	/**
	 * Parses the response's body.  The parsed response is stored in 'object'.
	 * This object is then used within the Driver to custom parse the response.
	 * Subclasses should override for custom processing.
	 * 
	 * @see IBMHandler
	 * @see IBMDriver
	 */
	protected void parseBody() {
		object = response.getBody();
	}
	
	/**
	 * Returns a String expressing the error that occurred.  Subclasses should
	 * override for custom processing.
	 * 
	 * @return String represents the error that occurred if !success()
	 */
	protected String parseError() {
		return response.getStatus() + " " + response.getPhrase();
	}
	
	/**
	 * Indicates if the request was successful or not.  Subclasses should
	 * override for custom processing.
	 * 
	 * @return true if the request was successful, false otherwise
	 */
	protected boolean success() {
		return response.getStatus() >= 200 && response.getStatus() <= 299;
	}
}
