//  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-2007 Amazon Digital Services, Inc. or its
//  affiliates.

package net.noderunner.amazon.s3;

import java.io.IOException;

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

/**
 * A Response object returned from AWSAuthConnection.getBucketLocation().
 * Parses the response XML and exposes the location constraint
 * via the {@link #getLocation()} method.
 */
public class LocationResponse extends Response {
	
    private String location;
    
    /**
     * Parse the response to a ?location query.
     */
    LocationResponse(HttpMethod method) throws IOException {
        super(method);
        if (isOk()) {
        	parse(new LocationResponseHandler());
        }
    }

    /**
     * Report the location-constraint for a bucket.
     * A value of null indicates an error; 
     * the empty string indicates no constraint;
     * and any other value is an actual location constraint value.
     */
    public String getLocation() {
        return location;
    }

    /**
     * Helper class to parse LocationConstraint response XML
     */
    class LocationResponseHandler extends DefaultHandler {
        private StringBuilder currText = null;
        
        @Override
        public void startElement(String uri, String name, String qName, Attributes attrs) {
            if (name.equals("LocationConstraint")) {
                this.currText = new StringBuilder();
            }
        }

        @Override
        public void endElement(String uri, String name, String qName) {
            if (name.equals("LocationConstraint")) {
                location = this.currText.toString();
                this.currText = null;
            }
        }
        
        @Override
        public void characters(char ch[], int start, int length) {
            if (currText != null)
                this.currText.append(ch, start, length);
        }
    }
    
    @Override
    public String toString() {
    	return super.toString() + " location=" + location;
    }
    
}
