package com.example.checkregister;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import com.example.checkregister.R;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class CheckRegisterFileViewActivity extends Activity {
  private ArrayList<String> register;
  private ArrayAdapter<String> aa;
  private ListView fileListView;
  private Context context;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    setContentView(R.layout.file_view);
    fileListView = (ListView) findViewById(R.id.fileListView);
    register = getDatafileLines();
    aa = new ArrayAdapter<String>(this, android.R.layout.test_list_item,
        register);
    fileListView.setAdapter(aa);

    fileListView.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view, int position,
          long id) {
        String msg = "Position: " + position + " ID: " + id;
        Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        toast.show();
      }
    });
  }

  private ArrayList<String> getDatafileLines() {
    String datafile = CheckRegisterActivity.datafile;
    String line = null;
    ArrayList<String> lines = new ArrayList<String>();
    FileInputStream fis;
    try {
      fis = openFileInput(datafile);
    }
    catch (FileNotFoundException fnfe) {
      Log.d(getPackageName(), "Error opening " + datafile + " for read", fnfe);
      return lines;
    }
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(
          new DataInputStream(fis)));
      while ((line = in.readLine()) != null) {
        lines.add(line);
      }
      in.close();
    }
    catch (IOException ioe) {
      Log.d(getPackageName(), "Error reading " + datafile, ioe);
    }
    return lines;
  }

}
