package com.example.usstates;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CursorAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;



public class StatesImageAdapter extends CursorAdapter {

  public StatesImageAdapter(Context context, Cursor c) {
    super(context, c, 0);
  }
  
  private final class ViewHolder {
    public ImageView imageView;
    public TextView stateNameText;
    public int imageIndex;
    public int stateNameIndex;
  }

  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    ViewHolder holder = (ViewHolder)view.getTag();
    byte[] image = cursor.getBlob(holder.imageIndex);
    if (image != null) {
      holder.imageView.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
    }
    else {
      holder.imageView.setImageBitmap(Bitmap.createBitmap(140, 70, Bitmap.Config.RGB_565 ));
    }
    if (holder.stateNameText != null) {
      holder.stateNameText.setText(cursor.getString(holder.stateNameIndex));
    }
  }

  @Override
  public View newView(Context context, Cursor cursor, ViewGroup parent) {
    ViewHolder holder = new ViewHolder();
    holder.imageView = new ImageView(context);
    holder.imageIndex = cursor.getColumnIndex(StatesDbAdapter.KEY_STATE_FLAG);
    holder.stateNameIndex = cursor.getColumnIndex(StatesDbAdapter.KEY_STATE_NAME);
    holder.imageView.setPadding(4,4,4,4);
    if (parent instanceof GridView) {
      holder.imageView.setLayoutParams(
        new GridView.LayoutParams(140,70));
      holder.imageView.setScaleType(ScaleType.CENTER_INSIDE);
      holder.stateNameText = null;
    }
    else if (parent instanceof Gallery) {
      holder.imageView.setLayoutParams(
          new Gallery.LayoutParams(
            new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT)));
      holder.imageView.setScaleType(ScaleType.FIT_CENTER);
      View pv = (View)parent.getParent();
      holder.stateNameText = (TextView)(pv.findViewById(R.id.stateNameText));
    }
    holder.imageView.setTag(holder);
    return holder.imageView;
  }

}
