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

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.nifty.cloud.ncs.NiftyCloudClientException;
import com.nifty.cloud.ncs.NiftyCloudResponse;
import com.nifty.cloud.ncs.http.HttpResponse;
import com.nifty.cloud.ncs.service.InitiateMultipartUploadResult;

/**
 * InitiateMultipartUploadの応答XML解析用クラスです。
 *
 */
public class InitiateMultipartUploadParser extends AbstractStorageResponseParser<InitiateMultipartUploadResult>
{

	public InitiateMultipartUploadParser() throws NiftyCloudClientException
	{
		super();
	}

	@Override
	public NiftyCloudResponse<InitiateMultipartUploadResult> parse( HttpResponse response) throws Exception
	{
		NiftyCloudResponse<InitiateMultipartUploadResult> ncsResponse = super.parseMetaData(response);
		InitiateMultipartUploadUnmarshaller unmarshaller = new InitiateMultipartUploadUnmarshaller();
		parseXml(unmarshaller, response.getContent());
		InitiateMultipartUploadResult initiateMultipartUploadResult = unmarshaller.getResult();

		ncsResponse.setResult(initiateMultipartUploadResult);

		return (ncsResponse);
	}


	private class InitiateMultipartUploadUnmarshaller extends DefaultHandler
	{

		private InitiateMultipartUploadResult result;
		private StringBuffer text = null;

		public InitiateMultipartUploadUnmarshaller()
		{
			super();
			result = new InitiateMultipartUploadResult();
			text = new StringBuffer();
		}

		public InitiateMultipartUploadResult getResult() {
			return result;
		}

		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException
		{
			if (localName.equals("Bucket"))
			{
				result.setBucketName(text.toString());
			} else if (localName.equals("Key"))
			{
				result.setKey(text.toString());
			} else if (localName.equals("UploadId"))
			{
				result.setUploadId(text.toString());
			}
			text = new StringBuffer();
		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			text.append(ch, start, length);
		}

	}
}
