package com.nifty.cloud.ncs.service.parser;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nifty.cloud.ncs.NiftyCloudServiceException;
import com.nifty.cloud.ncs.http.HttpResponse;
import com.nifty.cloud.ncs.http.HttpResponseParser;
import com.nifty.cloud.ncs.service.StorageException;
import com.nifty.cloud.ncs.service.StorageHeadersImpl;
import com.nifty.cloud.ncs.util.XmlUtils;

/**
 * ニフクラストレージのエラー応答解析用クラスです。
 *
 */
public class StorageErrorResponseParser implements HttpResponseParser<NiftyCloudServiceException>
{

	private static final Log log = LogFactory.getLog(StorageErrorResponseParser.class);

	/**
	 * ニフクラストレージのエラー応答を解析します。
	 *
	 * @param response
	 * 			HTTP応答
	 *
	 * @return ニフクラストレージで発生した例外
	 *
	 * @throws Exception
	 */
	public NiftyCloudServiceException parse(HttpResponse response) throws Exception
	{
		if (response.getContent() == null
			|| response.getHttpMethod().equals("HEAD")) {
			String requestId = response.getHeader(StorageHeadersImpl.REQUEST_ID);
			String extendedRequestId = response.getHeader(StorageHeadersImpl.EXTENDED_REQUEST_ID);
			log.debug("RequestId: " + requestId);
			log.debug("ExtendedRequestId: " + extendedRequestId);

			StorageException e = new StorageException(response.getStatusMessage());
			e.setRequestId(requestId);
			e.setExtendedRequestId(extendedRequestId);

			return (e);
		}

		XmlUtils xmlUtils = new XmlUtils(response.getContent());
		String message = xmlUtils.getString("Error/Message");
		String errorCode = xmlUtils.getString("Error/Code");
		String requestId = xmlUtils.getString("Error/RequestId");
		String extendedRequestId = xmlUtils.getString("Error/HostId");

		StorageException e = new StorageException(message);
		e.setStatusCode(response.getStatusCode());
		e.setErrorCode(errorCode);
		e.setRequestId(requestId);
		e.setExtendedRequestId(extendedRequestId);

		return (e);
	}
}
