//  This software code is made available "AS IS" without warranties of any
//  kind.  You may copy, display, modify and redistribute the software
//  code either by itself or as incorporated into your code; provided that
//  you do not remove any proprietary notices.  Your use of this software
//  code is at your own risk and you waive any claim against Amazon
//  Digital Services, Inc. or its affiliates with respect to your use of
//  this software code. (c) 2006 Amazon Digital Services, Inc. or its
//  affiliates.

package net.noderunner.amazon.s3;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.httpclient.HttpMethod;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Response for listing all buckets.
 */
public class ListAllBucketsResponse extends Response {
	
	private List<Bucket> entries;

	ListAllBucketsResponse(HttpMethod method) throws IOException {
		super(method);
		if (isOk()) {
    		entries = new ArrayList<Bucket>();
			parse(new ListAllMyBucketsHandler());
		}
	}

	/**
	 * Returns the bucket entries, unmodifiable.
	 */
	public List<Bucket> getEntries() {
		return Collections.unmodifiableList(entries);
	}
	
	class ListAllMyBucketsHandler extends DefaultHandler {

		private Bucket currBucket = null;
		private StringBuilder currText = null;
		private SimpleDateFormat iso8601Parser = null;

		public ListAllMyBucketsHandler() {
			super();
			this.iso8601Parser = new ISO801DateFormat();
			this.currText = new StringBuilder();
		}

        @Override
		public void startElement(String uri, String name, String qName,
				Attributes attrs) {
			if (name.equals("Bucket")) {
				this.currBucket = new Bucket();
			}
		}

        @Override
		public void endElement(String uri, String name, String qName) {
			if (name.equals("Bucket")) {
				entries.add(this.currBucket);
			} else if (name.equals("Name")) {
				if (currBucket == null)
					throw new IllegalStateException();
				this.currBucket.setName(this.currText.toString());
			} else if (name.equals("CreationDate")) {
				try {
					this.currBucket.setCreationDate(this.iso8601Parser
							.parse(this.currText.toString()));
				} catch (ParseException e) {
					throw new RuntimeException(
							"Unexpected date format in list bucket output", e);
				}
			}
			this.currText = new StringBuilder();
		}

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

	}

    
    @Override
    public String toString() {
    	return super.toString() + 
    		" entries=" + entries;
    }
}
