// Copyright 2005, Danger, Inc.  All Rights Reserved.
// This file is subject to the Danger, Inc. Sample Code License,
// which is provided in the file SAMPLE_CODE_LICENSE.
// Copies are also available from http://developer.danger.com/

package com.danger.text;

import danger.net.HTTPTransaction;
import danger.ui.*;
import danger.util.*;
import danger.text.span.*;
import java.io.IOException;

/**
 * This window has an EditText with some images.
 * Two of them are from resources; the other comes from the network.
 */
public class
Images
extends DemoWindow
{
	public
	Images()
	{
		this(Resources.ID_IMAGES_TEXT, Resources.ID_DEMO_IMAGES);
	}

	public
	Images(int rsrc, int title)
	{
		EditText et = new EditText();

		et.setSize(getWidth(), getHeight());
		et.setBorderShowsScrolling(true);
		et.setText(HTML.fromHTML(getApplication().getResources().getString(rsrc)));
		et.show();
		addChild(et);
		setFocusedChild(et);

		Object[] spans = et.getAllSpans(HTML.Image.class);
		if (spans != null)
		{
			for (int i = 0; i < spans.length; i++)
			{
				HTML.Image hi = (HTML.Image) spans[i];
				String src = hi.getSource();

				if (src.startsWith("http://"))
					Text.request(src, new ImageRequest(et, hi));
			}
		}

		setTitle(getApplication().getString(title));
	}

	private static class
	ImageRequest
	extends Text.HTTPRequest
	{
		public
		ImageRequest(Spannable buffer, BitmapSpan span)
		{
			mBuffer = buffer;
			mSpan = span;
		}

		public void
		received(HTTPTransaction ht)
		{
			if (ht.getResponse() != 200)
			{
				new AlertWindow(ht.getResponseMessage()).show();
				return;
			}

			try
			{
				Bitmap b = Bitmap.newFromEncodedData(ht.getBytes());
				BitmapSpan bs = new BitmapSpan(b, mSpan.getAlignment(), mSpan.getRelativeTo());

				mBuffer.setSpan(bs, mBuffer.getSpanStart(mSpan), mBuffer.getSpanEnd(mSpan), mBuffer.getSpanFlags(mSpan));
				mBuffer.removeSpan(mSpan);
			}
			catch (IOException ioe)
			{
				ioe.printStackTrace();
				return;
			}
		}

		private Spannable mBuffer;
		private BitmapSpan mSpan;
	}
}
