package com.example.fueltrack;

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 android.app.Activity;
import android.app.ListFragment;
import android.content.res.Configuration;
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 FuelFileViewActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.file_view);
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
      finish();
      return;
    }

    if (savedInstanceState == null) {
      FuelFileViewFragment fragment = new FuelFileViewFragment();
      fragment.setArguments(getIntent().getExtras());
      getFragmentManager().beginTransaction()
          .add(android.R.id.content, fragment).commit();
    }
  }

  public static class FuelFileViewFragment extends ListFragment {
    private ArrayList<String> mileage;
    private ArrayAdapter<String> aa;
    private ListView fileListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      fileListView = (ListView) getActivity().findViewById(R.id.fileListView);
      mileage = getDatafileLines();
      aa = new ArrayAdapter<String>(getActivity(),
          android.R.layout.test_list_item, mileage);
      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(getActivity(), msg, Toast.LENGTH_LONG);
          toast.show();
        }
      });
    }

    private ArrayList<String> getDatafileLines() {
      String datafile = FuelTrackActivity.datafile;
      String line = null;
      ArrayList<String> lines = new ArrayList<String>();
      FileInputStream fis;
      try {
        fis = getActivity().openFileInput(datafile);
      }
      catch (FileNotFoundException fnfe) {
        Log.d(getActivity().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(getActivity().getPackageName(), "Error reading " + datafile, ioe);
      }
      return lines;
    }

  }

}
