package com.smart.gtstrvl;

/* Copyright 2015 Esri
 *
 * 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.
 *
 */

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.esri.android.map.GraphicsLayer;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.tasks.geocode.LocatorFindParameters;
import com.esri.core.tasks.geocode.LocatorGeocodeResult;
import com.example.mountaintravel.adapter.SearchAdapter;
import com.example.mountaintravel.util.AppJsonFileReader;
import com.example.mountaintravel.util.FileSizeUtil;
import com.example.mountaintravel.util.StringChangeUtils;
import com.example.mountaintravel.util.StringUtils;
import com.example.mountaintravel.util.WebUtil;
import com.example.mountaintravel.variable.Variable;

/*
 * This fragment displays a dialog box which contains text fields for source and destination addresses.
 * It also contains two icons "My Location" and "Swap Addresses". When user clicks on My Location icon, the focused
 * text field displays the text "My Location". When "Swap Addresses" icon is clicked the addresses in the text boxes are swapped.
 * When the user clicks on the "Route" button, the addresses are geocoded to points which are then used by the RoutingSample activity to
 * display the route.
 * 
 */

@SuppressLint({ "NewApi", "ValidFragment" })
public class RoutingDialogFragment extends DialogFragment implements
		OnFocusChangeListener, OnClickListener {
	EditText et_source;
	EditText et_destination;
	static ProgressDialog dialog;
	static Handler handler;
	Button bGetRoute;
	onGetRoute mCallback;
	String source;
	String destination;
	ImageView img_sCancel, img_dCancel;
	static	Location location;
	static Boolean isMyLocation = false;
	//private List<List<String>> jsonData;
	private Map<String, Object> parameterMap;// 网络请求需传递的键/值
	static Point lfp_start_point = null;// 起始点point
	static Point lfp_dest_point = null;// 终始点point
	String lfp_start, lfp_dest;
	private String resultDestination;
	private String resultSource;
	String changeName;
	public RoutingDialogFragment(Location location) {
		super();
		this.location = location;
	}

	static public class MyRunnable implements Runnable {
		public void run() {
			dialog.dismiss();
		}
	}

	// Interface
	public interface onGetRoute {
		public void onDialogRouteClicked(Point p1, Point p2);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handler = new Handler();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mCallback = (onGetRoute) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement onDrawerListSelectedListener");
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		getDialog().getWindow().setBackgroundDrawable(
				new ColorDrawable(Color.TRANSPARENT));
		View view = inflater.inflate(R.layout.dialog_layout, container);
		et_source = (EditText) view.findViewById(R.id.et_source);
		et_source.setSelection(et_source.getText().toString().length());
		et_destination = (EditText) view.findViewById(R.id.et_destination);
		et_destination.requestFocus();
		img_sCancel = (ImageView) view.findViewById(R.id.iv_cancelSource);
		img_dCancel = (ImageView) view.findViewById(R.id.iv_cancelDestination);
		bGetRoute = (Button) view.findViewById(R.id.bGetRoute);
		et_source.addTextChangedListener(new MyTextWatcher(et_source));
		et_destination
				.addTextChangedListener(new MyTextWatcher(et_destination));
		et_source.setOnFocusChangeListener(this);
		et_destination.setOnFocusChangeListener(this);
		img_dCancel.setOnClickListener(this);
		img_sCancel.setOnClickListener(this);
		et_source.setOnClickListener(this);
		et_destination.setOnClickListener(this);
		bGetRoute.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				source = et_source.getText().toString().trim();
				destination = et_destination.getText().toString().trim();
				// If either of the edit text is empty, display the toast
				if (source.equals("") || destination.equals("")) {
					Toast.makeText(getActivity(), "不能为空", Toast.LENGTH_SHORT)
							.show();
					return;
				} else if (source.equals("我的位置")) {
					if (location != null) {
						isMyLocation = true;
						if (!source.equals(destination)) {
							geocode(source, destination);
						} else {
							Toast.makeText(getActivity(), "起始点和终点不能相同！",
									Toast.LENGTH_LONG).show();
							return;
						}
					} else {
						isMyLocation = false;
						Toast.makeText(getActivity(), "未获得起始地址，请重新输入！",
								Toast.LENGTH_SHORT).show();
						return;
					}
				} else if (source.equals(destination)) {
					Toast.makeText(getActivity(), "起始点和终点不能相同！",
							Toast.LENGTH_LONG).show();
					return;
				} else {
					geocode(source, destination);

				}
			}
		});

		// Removing title from the dialog box
		getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

		return view;
	}

	private void geocode(String address1, String address2) {
		try {
			// 检测address是否有效
			Geocoder gcoder = new Geocoder(address1, address2);
			gcoder.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	private class Geocoder extends AsyncTask<Void, Void, Void> {

		// Location Find Parameters for both source and destination addresses
		// Constructor
		public Geocoder(String findParams_start, String findParams_dest) {
			lfp_start = findParams_start;
			lfp_dest = findParams_dest;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Displaying the Process Dialog
			dialog = ProgressDialog.show(getActivity(), "路径规划","线路规划中 ...");
		}

		@Override
		protected Void doInBackground(Void... params) {
					try {
						if (isMyLocation) {
							lfp_start_point = new Point(location.getLongitude(),location.getLatitude());
							parameterMap = new HashMap<String, Object>();
							parameterMap.put("name", lfp_dest);
							resultDestination = WebUtil.post(Variable.URL_GTS, parameterMap);
						//	Log.i("TAG", "resultDestination = "+resultDestination);
							analysisJson(resultSource, lfp_start, 1);
						} else {
							//TODO 
							parameterMap = new HashMap<String, Object>();
							parameterMap.put("name", lfp_start);
							resultSource = WebUtil.post(Variable.URL_GTS, parameterMap);
						//	Log.i("TAG", "resultSource = "+resultSource+" \t lfp_start  = :" + lfp_start);
							analysisJson(resultSource, lfp_start, 0);
							parameterMap.clear();//清除map集合数据
							parameterMap.put("name", lfp_dest);//map 添加新数据
							resultDestination = WebUtil.post(Variable.URL_GTS, parameterMap);
						//	Log.i("TAG", "resultDestination = "+resultDestination+" \t lfp_dest  = :" + lfp_dest);
							analysisJson(resultDestination, lfp_start, 1);
						}
					} catch (Exception e) {
						System.out.println("请求失败 ");
						e.printStackTrace();
					}
			return null;
		}

		// The result of geocode task is passed as a parameter to map the
		// results

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			handler.post(new MyRunnable());
			if (lfp_start_point != null&&lfp_dest_point != null) {
				mCallback.onDialogRouteClicked(lfp_start_point, lfp_dest_point);
			}else if(lfp_start_point==null){
				Toast.makeText(getActivity(), "起始地址无效！", Toast.LENGTH_LONG)
				.show();
			}else if(lfp_dest_point==null){
				Toast.makeText(getActivity(), "终点地址无效！", Toast.LENGTH_SHORT)
				.show();
			}
		}
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

	}

	// Custom Listener for the Edit text views
	private class MyTextWatcher implements TextWatcher {

		private View view;

		private MyTextWatcher(View view) {
			this.view = view;
		}

		public void beforeTextChanged(CharSequence charSequence, int i, int i1,
				int i2) {

		}

		public void onTextChanged(CharSequence charSequence, int i, int i1,
				int i2) {
		}

		public void afterTextChanged(Editable editable) {

			// Displaying the cross icon when the edit text views are not empty
			String text = editable.toString();
			switch (view.getId()) {
			case R.id.et_source:
				if (text.length() > 0)
					img_sCancel.setVisibility(View.VISIBLE);
				else
					img_sCancel.setVisibility(View.INVISIBLE);
				break;
			case R.id.et_destination:
				if (text.length() > 0)
					img_dCancel.setVisibility(View.VISIBLE);
				else
					img_dCancel.setVisibility(View.INVISIBLE);
				break;
			}
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {

		// Checking the focus of the edit text and displaying the cross icon if
		// it is not empty
		switch (v.getId()) {
		case R.id.et_source:
			if (hasFocus && et_source.getText().toString().length() > 0)
				img_sCancel.setVisibility(View.VISIBLE);
			else
				img_sCancel.setVisibility(View.INVISIBLE);
			break;
		case R.id.et_destination:
			if (hasFocus && et_destination.getText().toString().length() > 0)
				img_dCancel.setVisibility(View.VISIBLE);
			else
				img_dCancel.setVisibility(View.INVISIBLE);

			break;

		}
	}

	// OnClick events for the icons on the dialog box
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_cancelSource:
			// Clearing the text
			et_source.getText().clear();
			break;
		case R.id.iv_cancelDestination:
			// Clearing the text
			et_destination.getText().clear();
			break;
		case R.id.et_source:
			et_source.setCursorVisible(true);
			et_source.requestFocus();

			break;
		case R.id.et_destination:
			et_destination.setCursorVisible(true);
			et_destination.requestFocus();

			break;
		}
	}

/*	public void json(String name) {
		String jsonStr = AppJsonFileReader.getJson(getActivity(), name);
		jsonData = AppJsonFileReader.getjson(jsonStr);
	}*/

	public void analysisJson(String result, String n, int type) {
		HashMap<String, Object> sss = StringChangeUtils.toObject(result,
				HashMap.class);
		List<String> array = (List<String>) sss.get("result");
		int resultCount = array.size();
		// Log.i("TAG", "///////////********" + array.toString());
		//请求结果为空
		if (resultCount == 0) {
			if (type == 0) {
				lfp_start_point = null;
			} else {
				lfp_dest_point = null;
			}
			//一个请求结果
		} else if (resultCount == 1) {
			HashMap<String, Object> ddd = StringChangeUtils.toObject(
					array.get(0), HashMap.class);
			Object potionX = ddd.get("potionX");
			Object potionY = ddd.get("potionY");
			if (!potionX.equals("") && !potionY.equals("")) {
				double x = Double
						.parseDouble(StringUtils.toString(potionX));
				double y = Double
						.parseDouble(StringUtils.toString(potionY));
				if (type == 0) {
					lfp_start_point = new Point(x, y);
				//	Log.i("TAG", "lfp_start_point = :"+lfp_start_point.getX()+lfp_start_point.getY());
				} else {
					lfp_dest_point = new Point(x, y);
				//	Log.i("TAG", "lfp_dest_point = :"+lfp_dest_point.getX()+lfp_dest_point.getY());
				}
			}
			//多个请求结果
		} else {
			for (int i = 0; i < resultCount; i++) {
				HashMap<String, Object> ddd = StringChangeUtils.toObject(
						array.get(i), HashMap.class);
				String name = StringUtils.toString(ddd.get("name"));
				if (name.equals(n)) {
					Object potionX = ddd.get("potionX");
					Object potionY = ddd.get("potionY");
					if (!potionX.equals("") && !potionY.equals("")) {
						double x = Double
								.parseDouble(StringUtils.toString(potionX));
						double y = Double
								.parseDouble(StringUtils.toString(potionY));
						if (type == 0) {
							lfp_start_point = new Point(x, y);
						//	Log.i("TAG", "lfp_start_point = :"+lfp_start_point.getX()+lfp_start_point.getY());
						} else {
							lfp_dest_point = new Point(x, y);
						//	Log.i("TAG", "lfp_dest_point = :"+lfp_dest_point.getX()+lfp_dest_point.getY());
						}
					}
				}

			}
		}
	}

}
