/* Copyright (c) 2008 -- CommonsWare, LLC

	 Licensed under the Apache License, Version 2.0 (the "License");
	 you may not use this file except in compliance with the License.
	 You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

	 Unless required by applicable law or agreed to in writing, software
	 distributed under the License is distributed on an "AS IS" BASIS,
	 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	 See the License for the specific language governing permissions and
	 limitations under the License.
*/
	 
package com.commonsware.tourit;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationProvider;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.NumberInputMethod;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;

public class TourEditActivity extends Activity
	implements AdapterView.OnItemSelectedListener {
	private static final int SAVE_ID = Menu.FIRST+1;
	private static final int HELP_ID = Menu.FIRST+100;
	private static final int CLOSE_ID = Menu.FIRST+2;
	private static final String URI_KEY="uri";
	private static final String JSON_KEY="json";
	
	private Tour tour;
	private EditText dir_distance;
	private EditText pt_lat;
	private EditText pt_long;
	private EditText pt_ele;
	private Cursor c;
	private Waypoint current;
	private LocationProvider provider=null;
	private LocationManager myLocationManager=null;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.edit);
		
		myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		dir_distance=(EditText)findViewById(R.id.dir_distance);
		pt_lat=(EditText)findViewById(R.id.pt_lat);
		pt_long=(EditText)findViewById(R.id.pt_long);
		pt_ele=(EditText)findViewById(R.id.pt_ele);
		
		dir_distance.setInputMethod(new FloatInputMethod());
		
		if (getIntent()!=null && getIntent().getData()!=null) {
			try {
				c=managedQuery(getIntent().getData(), Tour.PROJECTION, null, null);
				c.first();
				tour=new Tour(getIntent().getData(), c);
				load();
			}
			catch (Throwable t) {
				android.util.Log.e("TourIt", "Exception creating tour", t);
			}
		}
		
		if (icicle!=null && tour==null) {
			try {
				Uri url=Uri.parse(icicle.getString(URI_KEY));
				
				c=managedQuery(url, Tour.PROJECTION, null, null);
				c.first();
				tour=new Tour(url, c);
				tour.updateRouteFromJSON(icicle.getString(JSON_KEY));
				load();
			}
			catch (Throwable t) {
				android.util.Log.e("TourIt", "Exception creating tour", t);
			}
		}
		
 		Spinner spin=(Spinner)findViewById(R.id.spinner);
		spin.setOnItemSelectedListener(this);
		
		ArrayAdapter<Waypoint> aa=new ArrayAdapter<Waypoint>(this,
															R.layout.spinner,
															tour.getRoute());
		
		aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(aa);
		
		Button btn=(Button)findViewById(R.id.fillin);
		
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (provider!=null) {
					Location loc=myLocationManager.getCurrentLocation(provider.getName());
					
					pt_lat.setText(new Double(loc.getLatitude()).toString());
					pt_long.setText(new Double(loc.getLongitude()).toString());
					pt_ele.setText(new Double(loc.getAltitude()).toString());
				}
			}
		});
	 }
	@Override
	public void onResume() {
		super.onResume();
		
		SharedPreferences prefs=getSharedPreferences(ConfigActivity.PREFS, 0);
		
		String providerName=prefs.getString(ConfigActivity.LOCATION_PROVIDER, null);
		
		if (providerName!=null) {
			for (LocationProvider p : myLocationManager.getProviders()) {
				if (p.getName().equals(providerName)) {
					provider=p;
					break;
				}
			}
		}
		
		if (provider==null) {
			Criteria crit=new Criteria();
			
			crit.setCostAllowed(true);
			crit.setSpeedRequired(false);
			crit.setBearingRequired(false);
			crit.setAltitudeRequired(false);
			
			provider=myLocationManager.getBestProvider(crit);
		}
	}
	
	@Override
	public void onFreeze(Bundle outState) {
		super.onFreeze(outState);
		
		outState.putString(URI_KEY, tour.getUrl().toString());
		outState.putString(JSON_KEY, tour.getRouteAsJSON());
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, SAVE_ID, "Save", R.drawable.ok)
				.setAlphabeticShortcut('s');
		menu.add(0, HELP_ID, "Help", R.drawable.help)
				.setAlphabeticShortcut('h');
		menu.add(0, CLOSE_ID, "Close", R.drawable.eject)
				.setAlphabeticShortcut('c');

		return(super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(Menu.Item item) {
		switch (item.getId()) {
			case SAVE_ID:
				save();
				return(true);
				
			case HELP_ID:
				Intent i=new Intent(this, HelpActivity.class);
				
				i.putExtra(HelpActivity.PAGE, "edit");
				startActivity(i);
				return(true);
				
			case CLOSE_ID:
				finish();
				return(true);
		}

		return(super.onOptionsItemSelected(item));
	}
	
	public void onItemSelected(AdapterView parent, View v, int position, long id) {
		saveStep();
		current=tour.getRoute().get(position);
		populateStep();
	}
	
	public void onNothingSelected(AdapterView parent) {
		saveStep();
		current=null;
		populateStep();
	}
	
	private void load() {
		setTitle("TourIt! - Edit "+tour.getTitle());
		
		if (tour.getRoute().size()>0) {
			current=tour.getRoute().get(0);
			populateStep();
		}
		else {
			current=null;
			populateStep();
		}
	}
	
	private void save() {
		if (tour==null) {
			ContentValues values=new ContentValues();
			
			values.put(Provider.Tours.TITLE, tour.getTitle());
			
			Uri url=getContentResolver().insert(Provider.Tours.CONTENT_URI, values);
			
			c=managedQuery(url, Tour.PROJECTION, null, null);
			c.first();
			
			try {
				tour=new Tour(url, c);
			}
			catch (Throwable t) {
				android.util.Log.e("TourIt", "Exception creating tour", t);
				Toast.makeText(this, R.string.save_failed, 2000).show();
				return;
			}
		}
		
		saveStep();
		
		try {
			tour.prepForSave();
			
			if (c.commitUpdates()) {
				c.requery();
				c.first();
				load();
			}
			else {
				Toast.makeText(this, R.string.save_failed, 2000).show();
			}
		}
		catch (Throwable t) {
			android.util.Log.e("TourIt", "Exception creating tour", t);
			Toast.makeText(this, R.string.save_failed, 2000).show();
			return;
		}
	}
	
	private void populateStep() {
		Direction dir=null;
		
		pt_lat.setText("");
		pt_long.setText("");
		pt_ele.setText("");
		dir_distance.setText("");
		dir_distance.setEnabled(false);
		
		if (current!=null) {
			if (current.getLatitude()!=null) {
				pt_lat.setText(current.getLatitude().toString());
			}
			
			if (current.getLongitude()!=null) {
				pt_long.setText(current.getLongitude().toString());
			}
			
			if (current.getElevation()!=null) {
				pt_ele.setText(current.getElevation().toString());
			}
		
			dir=current.getToDirection();
			
			if (dir!=null) {
				if (dir.getDistance()!=null) {
					dir_distance.setText(dir.getDistance().toString());
					dir_distance.setEnabled(true);
				}
			}
		}
	}
	
	private void saveStep() {
		if (current!=null) {
			try {
				current.setLatitude(fieldToDouble(pt_lat));
				current.setLongitude(fieldToDouble(pt_long));
				current.setElevation(fieldToDouble(pt_ele));
				current.setLatitude(fieldToDouble(pt_lat));
				
				Direction dir=current.getToDirection();
				
				if (dir!=null) {
					dir.setDistance(fieldToDouble(dir_distance));
				}
			}
			catch (Throwable t) {
				android.util.Log.e("TourIt", "Exception saving waypoint", t);
				Toast.makeText(this, R.string.edit_failed, 2000).show();
			}
		}
	}
	
	private Double fieldToDouble(EditText field) {
		String value=field.getText().toString();
		Double result=new Double(0.0d);
		
		try {
			result=new Double(value);
		}
		catch (Throwable t) {
			// not a number, treat as 0
		}
		
		return(result);
	}
	
	class FloatInputMethod extends NumberInputMethod {
		private static final String CHARS="0123456789-.";
		
		protected char[] getAcceptedChars() {
			return(CHARS.toCharArray());
		}
	}
}