package com.usai.apex;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.baidu.mapapi.map.SupportMapFragment;
import com.usai.Contacts.Contact;
import com.usai.Contacts.ContactsManager;

//import com.baidu.mapapi.MKGeneralListener;
//import com.baidu.mapapi.map.MKEvent;

public class InnerMapActivity extends AppCompatActivity implements BaiduMapFragment.BaiduMarkerClickListener,ServiceLocationFragment.MarkerClickListener
{
//	public static boolean		m_bKeyRight				= true;
//	BMapManager					mBMapManager			= null;

//    public String strKey = getString(R.string.baidu_key);//"nqBQoSDbxrslhuzW91uViQX7";//release
	private static final String	LTAG					= "test";
	SupportMapFragment			map;

	boolean						m_bhasgoogleframework	= true;  

//	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(),
//						"?????? MyApplication.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 boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			// Intent myIntent = new Intent();
			// myIntent = new Intent(EditActivity.this, tabActivity.class);
			// startActivity(myIntent);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Intent intent = new Intent();
		switch (item.getItemId())
		{
			case android.R.id.home:
				finish();
				break;

			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void setCustomActionBar() {
		ActionBar.LayoutParams lp =new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
		View mActionBarView = LayoutInflater.from(this).inflate(R.layout.actionbar_customtitle, null);

		TextView titleview = mActionBarView.findViewById(R.id.title);
		titleview.setText("Service Location");
		setTitle("Service Location");
		ActionBar actionBar = getSupportActionBar();
		actionBar.setCustomView(mActionBarView, lp);
//		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);


		actionBar.setDisplayShowTitleEnabled(true);
	}

	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		mContext = this;
		PackageInfo packageInfo;
		try
		{
			packageInfo = this.getPackageManager().getPackageInfo(
					"com.google.android.gms", 0);

		}
		catch (NameNotFoundException e)
		{
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo == null)
		{
			m_bhasgoogleframework = false;
			System.out.println("没有安装");
		}
		else
		{
			m_bhasgoogleframework = true;
			System.out.println("已经安装");
		}
		// setUpMapIfNeeded();

//		m_bhasgoogleframework = false;




//		m_bhasgoogleframework= true;

		Fragment slFragment = null;
		if (m_bhasgoogleframework )
		{
			setContentView(R.layout.activity_inner_map);
			slFragment = new ServiceLocationFragment();
			((ServiceLocationFragment)slFragment).markerClickListener = this;
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.replace(R.id.inner_map, slFragment);
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			ft.addToBackStack("Location");
			ft.commit();

		}
		else
		{
//			if (mBMapManager == null)
//			{
//				mBMapManager = new BMapManager(getApplicationContext());
//				/**
//				 * ??????BMapManager???????????????????????????BMapManager
//				 */
//				mBMapManager.init(strKey, new MyGeneralListener());
//			}
			
//			f.initEngineManager(this);
			setContentView(R.layout.activity_inner_map);
//			Log.d(LTAG, "onCreate");
//			// setContentView(R.layout.activity_main);
//			map = SupportMapFragment.newInstance();
			BaiduMapFragment f  = new BaiduMapFragment();
			FragmentManager manager = getSupportFragmentManager();
			manager.beginTransaction().add(R.id.inner_map, f, "map_fragment")
					.commit();
			f.markerClickListener = this;
		}

		setCustomActionBar();

//		LocationDetail detail = new LocationDetail("Kerry Freight (USA), Inc","3200 NW 67th Ave. Bldg. 3 Suite 390 Miami, FL 33122 Miami","+(305)12345678","+(305)4567890",null,"mario.alfonso@kerrylogistics.com");
//		markerClicked(detail);
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu)
	// {
	// // Inflate the menu; this adds items to the action bar if it is present.
	// getMenuInflater().inflate(R.menu.inner_map, menu);
	// return true;
	// }
	// private void setUpMapIfNeeded() {
	// // Do a null check to confirm that we have not already instantiated the
	// map.
	// if (mMap == null) {
	// // Try to obtain the map from the SupportMapFragment.
	// mMap = ((SupportMapFragment)
	// getSupportFragmentManager().findFragmentById(R.id.map))
	// .getMap();
	// // Check if we were successful in obtaining the map.
	// if (mMap != null) {
	// setUpMap();
	// }
	// }
	// }


	@Override
	public void markerClicked(LocationDetail detail) {

		if (detail == null) {
			return;
		}
		String homePage = "http://www.apexshipping.com";
		Bitmap photo = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);

		final Contact contact = new Contact();
		contact.setName(detail.Name);
		contact.setAddress(detail.Addr);
		contact.setNumber(detail.Tel);
		contact.setFax(detail.Fax);
		contact.setEmail(detail.Email);
		contact.setHomePage(homePage);
		contact.setPhoto(photo);

		final ContactsManager cm = new ContactsManager(this.getContentResolver());
		if (cm.contactExist(contact.getName())) {

			new AlertDialog.Builder(this)
					.setTitle("Warning")
					.setMessage(contact.getName() + " has exist in contacts,do you want to update it?")
					.setNegativeButton("No", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 不更新则直接查看
//							cm.insertContact(contact,mContext);
							Contact existContact = cm.searchContact(contact.getName());
							String contactId = cm.getContactID(existContact.getName());
							Intent editIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/contacts/"+contactId));
							startActivity(editIntent);
						}
					})
					.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {

							//Intent.ACTION_INSERT_OR_EDIT
							//参考 https://blog.csdn.net/mls1454001840/article/details/60764351 之二
							Contact existContact = cm.searchContact(contact.getName());
							cm.updateContact(existContact,contact);
							// 显示编辑界面
							String contactId = cm.getContactID(existContact.getName());
							cm.editContact(contactId,mContext);


						}
					})
					.show();
		} else {
			// 自动保存，然后显示编辑
//			cm.addContact(contact,true);
//			// 显示编辑界面
//			String contactId = cm.getContactID(contact.getName());
//			editContact(contactId);

			// 需要用户手动保存
			cm.insertContact(contact,mContext);
		}

	}


}
