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;

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;

	protected abstract HttpUriRequest createRequest();

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

		try {
			HttpUriRequest httpRequest = createRequest();
			HttpResponse httpResponse = httpClient.execute(
					httpRequest
					);
			if (DEBUG_LOGD) {
				Log.d(LOG_TAG, "XmlLoader HTTP response>");
				Log.d(LOG_TAG, httpResponse.getStatusLine().getReasonPhrase());
				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) {
			dispatchOnOccurredError("UnsupportedEncodingException");
			Log.d(LOG_TAG, e.getMessage(), e);
		} catch (ClientProtocolException e) {
			dispatchOnOccurredError("ClientProtocolException");
			Log.d(LOG_TAG, e.getMessage(), e);
		} catch (IOException e) {
			dispatchOnOccurredError("IOException");
			Log.d(LOG_TAG, e.getMessage(), e);
		} finally {
			if (inDownload != null) {
				try {
					inDownload.close();
				} catch (IOException e) {
					Log.d(LOG_TAG, e.getMessage(), e);
				}
			}
		}
		
	}

}
