package simplecloud.storage.providers.nirvanix;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import base.connection.ResponseHandler;
import base.interfaces.IResponse;

public class NirvanixHandler extends ResponseHandler {
	
	private Document document;
	private String responseCode;
	private String phrase;

	public NirvanixHandler(IResponse response) {
		super(response);
		this.responseCode = null;
		this.phrase = null;
	}
	
	protected void parseBody() {
		this.object = document;
	}
	
	protected String parseError() {
		if (responseCode == null || phrase == null) {
			return super.parseError();
		}
		return responseCode + ": " + phrase;
	}
	
	protected boolean success() {
		// Simple error occurred
		if (response.getStatus() != 200) {
			return super.success();
		}
		
		// Further investigation needed; look at the body... bum bum bum.
		try {
			// Parse out document for future consumption
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			document = db.parse(response.getItem().getContent());
			
			// Parse response for status
			Element elem = document.getDocumentElement();
			XPath xpath = XPathFactory.newInstance().newXPath();
			responseCode = xpath.evaluate("/Response/ResponseCode", elem);
			if (!responseCode.equals("0")) {
				phrase = xpath.evaluate("/Response/ErrorMessage", elem);
				return false;
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return true;	// Not guilty!
	}
}
