package jp.sourceforge.nicoro;

import static jp.sourceforge.nicoro.Log.LOG_TAG;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicLineFormatter;

import android.os.Handler;

public abstract class HttpXmlLoader extends XmlLoader {
	private static final boolean DEBUG_LOGV = Release.IS_DEBUG && true;
	private static final boolean DEBUG_LOGD = Release.IS_DEBUG && true;
	
	private HttpUriRequest mHttpRequest;
	
	protected HttpXmlLoader() {
	    super();
	}
	protected HttpXmlLoader(Handler handler) {
	    super(handler);
	}

	protected abstract HttpUriRequest createRequest();

	@Override
	public void run() {
		DefaultHttpClient httpClient = Util.createHttpClient();
		httpClient.getCookieStore().clear();
		InputStream inDownload = null;

		try {
			HttpUriRequest httpRequest = createRequest();
			mHttpRequest = httpRequest;
			HttpResponse httpResponse = httpClient.execute(
					httpRequest
					);
			if (DEBUG_LOGD) {
				Log.d(LOG_TAG, "XmlLoader HTTP response>");
                Log.d(LOG_TAG, BasicLineFormatter.formatStatusLine(httpResponse.getStatusLine(), null));
				Util.logHeaders(LOG_TAG, httpResponse.getAllHeaders());
			}
			
			int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
			if (httpStatusCode == HttpStatus.SC_OK) {
				HttpEntity entityInput = httpResponse.getEntity();
				inDownload = entityInput.getContent();
				
				boolean result = readAndCreateData(inDownload);
				
				if (result) {
					dispatchOnFinished();
				} else {
					dispatchOnOccurredError("XML parse failed");
				}
			} else {
				// エラー
				String errorMessage = "HTTP Status Code: " + httpStatusCode;
				dispatchOnOccurredError(errorMessage);
			}
			
		} catch (UnsupportedEncodingException e) {
			String errorMessage = e.toString();
			dispatchOnOccurredError(errorMessage);
			Log.d(LOG_TAG, errorMessage, e);
		} catch (ClientProtocolException e) {
			String errorMessage = e.toString();
			dispatchOnOccurredError(errorMessage);
			Log.d(LOG_TAG, errorMessage, e);
		} catch (IOException e) {
			String errorMessage = e.toString();
			dispatchOnOccurredError(errorMessage);
			Log.d(LOG_TAG, errorMessage, e);
		} finally {
			if (inDownload != null) {
				try {
					inDownload.close();
				} catch (IOException e) {
					Log.d(LOG_TAG, e.toString(), e);
				}
			}
		}
		
	}

	@Override
	protected void shutdownNetwork() {
		if (mHttpRequest != null && !mHttpRequest.isAborted()) {
			mHttpRequest.abort();
		}
	}
}
