package com.example.fueltrack;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class FuelCursorAdapter extends CursorAdapter {
	private final LayoutInflater inflater;
	private static String distanceUnit = "Km";
	private static String fuelUnit = "L";
	private static SharedPreferences prefs;

	private final class ViewHolder {
		public TextView date;
		public TextView distance;
		public TextView fuel;
		public TextView cost;
		public int dateIndex;
		public int distanceIndex;
		public int fuelIndex;
		public int costIndex;
	}
	
	public FuelCursorAdapter(Context context, Cursor c) {
		super(context, c, FLAG_REGISTER_CONTENT_OBSERVER);
		inflater = LayoutInflater.from(context);
		prefs = PreferenceManager.getDefaultSharedPreferences(context);
	}

	@Override
	public void bindView(View view, Context context, Cursor c) {
		distanceUnit = prefs.getString("distance_unit", "Distance");
		fuelUnit = prefs.getString("fuel_unit", "Fuel");
		
		/** Without ViewHolder: 
		TextView date = (TextView)view.findViewById(R.id.dateView);
		TextView distance = (TextView)view.findViewById(R.id.distanceView);
		TextView fuel = (TextView)view.findViewById(R.id.fuelView);
		TextView cost = (TextView)view.findViewById(R.id.costView);
		date.setText(c.getString(c.getColumnIndex(MileageDBAdapter.KEY_DATE)));	
		distance.setText(c.getString(c.getColumnIndex(MileageDBAdapter.KEY_DISTANCE)) + distanceUnit);	
		fuel.setText(c.getString(c.getColumnIndex(MileageDBAdapter.KEY_FUEL)) + fuelUnit);	
		cost.setText("$" + c.getString(c.getColumnIndex(MileageDBAdapter.KEY_COST)));
		**/
		
		/** With ViewHolder:  **/
		ViewHolder holder = (ViewHolder)view.getTag();
		if (holder == null) {
			holder = new ViewHolder();
			holder.date = (TextView)view.findViewById(R.id.dateView);
			holder.distance = (TextView)view.findViewById(R.id.distanceView);
			holder.fuel = (TextView)view.findViewById(R.id.fuelView);
			holder.cost = (TextView)view.findViewById(R.id.costView);
			holder.dateIndex = c.getColumnIndex(FuelDbAdapter.KEY_DATE);
			holder.distanceIndex = c.getColumnIndex(FuelDbAdapter.KEY_DISTANCE);
			holder.fuelIndex = c.getColumnIndex(FuelDbAdapter.KEY_FUEL);
			holder.costIndex = c.getColumnIndex(FuelDbAdapter.KEY_COST);
			view.setTag(holder);
		}
		holder.date.setText(c.getString(holder.dateIndex));	
		holder.distance.setText(c.getString(holder.distanceIndex) + distanceUnit);	
		holder.fuel.setText(c.getString(holder.fuelIndex) + fuelUnit);	
		holder.cost.setText("$" + c.getString(holder.costIndex));
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		final View view = inflater.inflate(R.layout.mileage_list_item, null);		
		return view;
	}

}