package com.example.usstates;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

public class StatesGridActivity extends Activity {
  private StatesDbAdapter dba;
  private Cursor c;
  private int abbrIndex;
  private int nameIndex;
  private int nickIndex;
  private int capitalIndex;


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_states_grid);
    dba = new StatesDbAdapter((Context)this);
    c = dba.getAllStates();
    abbrIndex = c.getColumnIndex(StatesDbAdapter.KEY_STATE_ABBR);
    nameIndex = c.getColumnIndex(StatesDbAdapter.KEY_STATE_NAME);
    nickIndex = c.getColumnIndex(StatesDbAdapter.KEY_STATE_NICK);
    capitalIndex = c.getColumnIndex(StatesDbAdapter.KEY_STATE_CAPITAL);
    StatesImageAdapter sia = new StatesImageAdapter(this, c);
    GridView gridView = (GridView) findViewById(R.id.flagGridView);
    gridView.setAdapter(sia);
    gridView.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
        displayStateInfo();
      }
    });

  }
  
  private void displayStateInfo() {
    String msg = c.getString(nameIndex)
        + "\nAbbreviation: " + c.getString(abbrIndex)
        + "\nCapital: " + c.getString(capitalIndex)
        + "\nNickname: " + c.getString(nickIndex);
    Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();

  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_states_grid, menu);
    return true;
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int itemid = item.getItemId();
    switch (itemid) {
    case R.id.flagItem:
      startActivity(new Intent("com.example.usstates.FLAGS"));
      break;
    }
    return true;
  }

}
