package com.usai.apex;

//import com.google.android.gms.maps.SupportMapFragment;

//import baidumapsdk.demo.DemoApplication;
//import baidumapsdk.demo.DemoApplication.MyGeneralListener;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.SupportMapFragment;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.usai.util.Network;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class BaiduMapFragment extends Fragment
{
	private SearchTask				m_task				= null;
	String							fragment_content	= null;
	private MapView					mMapView			= null;
	private MyOverlay				mOverlay			= null;
	// private OverlayItem mCurItem = null;
	// private Button button = null;
	private ArrayList<OverlayItem>	mItems				= null;
	private PopupOverlay			pop					= null;
	SupportMapFragment				fragment;
	BMapManager						mBMapManager		= null;
	public static boolean			m_bKeyRight			= true;
	HashMap<String, LocationDetail>	marker_detail		= new HashMap<String, LocationDetail>();
	OverlayItem						m_curitem			= null;

	public class MyOverlay extends ItemizedOverlay
	{

		public MyOverlay(Drawable defaultMarker, MapView mapView)
		{
			super(defaultMarker, mapView);
		}

		@Override
		public boolean onTap(int index)
		{
			Log.d("baidumap...................", "ontap");
			View viewCache = getActivity().getLayoutInflater().inflate(
					R.layout.marker_view, null);

			TextView tv_title = (TextView) viewCache
					.findViewById(R.id.tv_title);
			TextView tv_info = (TextView) viewCache.findViewById(R.id.tv_info);

			OverlayItem item = getItem(index);

			tv_title.setText(item.getTitle());
			tv_info.setText(item.getSnippet());
			m_curitem = item;
			pop.showPopup(viewCache, item.getPoint(), 32);
			return true;
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mMapView)
		{
			Log.d("baidu map demo ", "hide pop");
			if (pop != null)
			{

				pop.hidePop();
				// mMapView.removeView(button);
			}
			return false;
		}

	}

	void AddMarker()
	{

		if (mMapView == null)
		{

			Log.d("onResume", "get map from fragment");
			mMapView = fragment.getMapView();
			if (mMapView == null)
				return;
		}

		try
		{
			JSONObject jsobj = new JSONObject(fragment_content);

			int count = jsobj.getInt("total");

			JSONObject objrecords = jsobj.getJSONObject("records");
			mOverlay = new MyOverlay(getResources().getDrawable(
					R.drawable.ic_marker), mMapView);
			for (int i = 0; i < count; i++)
			{
				// offset++;

				JSONObject objrec = objrecords.getJSONObject("record" + i);
				String area = objrec.getString("area");
				String company = objrec.getString("company");
				String city = objrec.getString("city");
				String longitude = objrec.getString("longitude");
				String latitude = objrec.getString("latitude");
				String address = objrec.getString("address");
				String telephone = objrec.getString("telephone");
				String fax = objrec.getString("fax");
				String contact = objrec.getString("contact");
				String email = objrec.getString("email");

				LocationDetail detail = new LocationDetail(company, address,
						telephone, fax, contact, email);
				marker_detail.put(company, detail);

				/**
				 * 准备overlay 数据
				 */
				GeoPoint p1 = new GeoPoint(
						(int) (Double.parseDouble(latitude) * 1E6),
						(int) (Double.parseDouble(longitude) * 1E6));
				OverlayItem item1 = new OverlayItem(p1, company, city + "\n"
						+ area);

				/**
				 * 将item 添加到overlay中 注意： 同一个itme只能add一次
				 */
				mOverlay.addItem(item1);

			}
			/**
			 * 保存所有item，以便overlay在reset后重新添加
			 */
			mItems = new ArrayList<OverlayItem>();
			mItems.addAll(mOverlay.getAllItem());
			/**
			 * 将overlay 添加至MapView中
			 */
			mMapView.getOverlays().add(mOverlay);
			/**
			 * 刷新地图
			 */
			mMapView.refresh();
			PopupClickListener popListener = new PopupClickListener()
			{
				@Override
				public void onClickedPopup(int index)
				{
					Log.d("baidu map.......", "popup on click");
					pop.hidePop();

					mMapView.refresh();
					Intent intent = new Intent();
					intent.setClass(getActivity(), LocationDetailActivity.class);

					String markertext = m_curitem.getTitle();

					intent.putExtra("detail", marker_detail.get(markertext));
					// // intent.putExtra("password", password);
					// intent.putExtra("function_name", function_name);
					// intent.putExtra("behavior", Network.BEHAVIOR_SEARCH);
					startActivity(intent);

				}
			};
			pop = new PopupOverlay(mMapView, popListener);
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void requestloactions()
	{

		if (m_task != null)
		{
			return;
		}

		if (fragment_content != null)
		{
			// LayoutInflater inflater = (LayoutInflater)
			// ApexTrackingApplication
			// .get_instance().getSystemService(
			// Context.LAYOUT_INFLATER_SERVICE);
			// init(fragment_content,inflater);
			return;
		}
		// mStatusMessageView.setText(R.string.str_Loading);
		// showProgress(true);
		m_task = new SearchTask();

		// TextView text_page = (TextView) view_page_footer
		// .findViewById(R.id.text_page);
		// text_page.setText("Loading...");
		// text_page.setEnabled(false);
		m_task.execute();

	}

	class SearchTask extends AsyncTask<Void, Void, Boolean>
	{
		int	errorcode;

		// boolean bfinish = false;

		@Override
		protected Boolean doInBackground(Void... params)
		{
			Log.d("SearchTask", "doInBackground");
			if (!Network.NetworkIsAvailable())

			{
				errorcode = Network.RESULT_NET_NOTAVAILABLE;
				return false;
			}
			String jstr = Network.get_servicelocation();

			if (jstr == null || jstr.length() <= 0)
			{
				// Log.d(TAG, "json is wrong");

				errorcode = Network.RESULT_NET_ERROR;
				return false;
			}

			JSONObject jsobj;
			//
			// array = new JSONArray(json);
			try
			{
				jsobj = new JSONObject(jstr);
				// if (searchresult.get_fieldscount() == 0)
				// {
				// JSONObject objfields = jsobj.getJSONObject("fields");
				// if (objfields != null)
				// searchresult.init_fields(objfields.toString());
				// }
				int count = jsobj.getInt("total");
				// if (count < limit)
				// bfinish = true;
				JSONObject objrecords = jsobj.getJSONObject("records");
				if (objrecords != null)
				{
					fragment_content = jstr;
					errorcode = Network.RESULT_TRUE;

					return true;
				}
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			errorcode = Network.RESULT_NET_ERROR;
			return false;
		}

		@Override
		protected void onPostExecute(Boolean success)
		{
			String tag = "onPostExecute@BaiduMapFragment";
			Log.d(tag, "entry");
			m_task = null;
			// showProgress(false);

			switch (errorcode)
			{
				case Network.RESULT_NET_NOTAVAILABLE:
				{
					Toast toast = Toast.makeText(
							ApexTrackingApplication.get_instance(),
							getText(R.string.msg_connection_none),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				}
				case Network.RESULT_NET_ERROR:
				{
					Toast toast = Toast.makeText(
							ApexTrackingApplication.get_instance(),
							getText(R.string.msg_net_error), Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				}
				case Network.RESULT_ERROR:
				// case Network.RESULT_RESPONSE_NULL:
				{
					Toast toast = Toast.makeText(
							ApexTrackingApplication.get_instance(),
							getText(R.string.msg_net_resulterror),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				}

				default:
					break;
			}

			if (success)
			{
				AddMarker();
				//
				// if (bfinish)
				// {
				// // getListView().removeFooterView(view_page_footer);
				// // Toast.makeText(AnnouncementActivity.this, "Load all!",
				// // Toast.LENGTH_LONG).show();
				//
				// TextView tv = (TextView) view_page_footer
				// .findViewById(R.id.text_page);
				// tv.setText("No more items");
				// tv.setEnabled(false);
				// }
				// else
				// {
				// TextView tv = (TextView) view_page_footer
				// .findViewById(R.id.text_page);
				// tv.setText("More...");
				// tv.setEnabled(true);
				// }
				// adapter.notifyDataSetChanged();
				// // getListAdapter().notifyDataSetChanged;
				// // BaseAdapter mJson = null;
				// // mJson.notifyDataSetChanged();
			}

			super.onPostExecute(success);
		}

		@Override
		protected void onCancelled()
		{
			m_task = null;
			// showProgress(false);
		}
	}

	public void initEngineManager(Context context)
	{
		String strKey = ApexTrackingApplication.get_instance().getString(
				R.string.baidu_key);
		if (mBMapManager == null)
		{
			mBMapManager = new BMapManager(context);
		}

		if (!mBMapManager.init(strKey, new MyGeneralListener()))
		{
			// Toast.makeText(getActivity().getApplicationContext(),
			// "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
		}
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	static class MyGeneralListener implements MKGeneralListener
	{

		@Override
		public void onGetNetworkState(int iError)
		{
			if (iError == MKEvent.ERROR_NETWORK_CONNECT)
			{
				// Toast.makeText(
				// ApexTrackingApplication.get_instance()
				// .getApplicationContext(), "您的网络出错啦！",
				// Toast.LENGTH_LONG).show();
			}
			else if (iError == MKEvent.ERROR_NETWORK_DATA)
			{
				// Toast.makeText(
				// ApexTrackingApplication.get_instance()
				// .getApplicationContext(), "输入正确的检索条件！",
				// Toast.LENGTH_LONG).show();
			}
			// ...
		}

		@Override
		public void onGetPermissionState(int iError)
		{
			// 非零值表示key验证未通过
			if (iError != 0)
			{
				// 授权Key错误：
				// Toast.makeText(
				// ApexTrackingApplication.get_instance()
				// .getApplicationContext(),
				// "请在 DemoApplication.java文件输入正确的授权Key,并检查您的网络连接是否正常！error: "
				// + iError, Toast.LENGTH_LONG).show();
				m_bKeyRight = false;
			}
			else
			{
				m_bKeyRight = true;
				// Toast.makeText(
				// ApexTrackingApplication.get_instance()
				// .getApplicationContext(), "key认证成功",
				// Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{

		super.onActivityCreated(savedInstanceState);
		initEngineManager(getActivity().getApplicationContext());

		FragmentManager fm = getChildFragmentManager();
		fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);

		if (fragment == null)
		{

			Log.d("onActivityCreated", "create support map fragment");
			fragment = SupportMapFragment.newInstance();
			;// .newInstance();
			fm.beginTransaction().replace(R.id.map, fragment).commit();
		}
		mMapView = fragment.getMapView();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		// return super.onCreateView(inflater, container, savedInstanceState);
		requestloactions();
		return inflater.inflate(R.layout.fragment_service_location, container,
				false);
	}

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

		Log.d("onResume", "get map from fragment");

		MapController controller = fragment.getMapView().getController();
		controller.setCenter(new GeoPoint((int) (29.945 * 1E6),
				(int) (106.404 * 1E6)));
		controller.setZoom(5);
	}

}
