package com.usai.apex;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;


import com.usai.util.commonUtil;
import com.usai.util.dbUtil;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TabHost;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

public class DetailActivity extends FragmentActivity implements
		TabHost.TabContentFactory
{
	boolean showlogin = false;
	// int radomid = 1 + (int) (Math.random() * 15);
	TabHost							mTabHost;
	LinkedHashMap<String, Integer>	tabmap	= new LinkedHashMap<String, Integer>();
	HashMap<String,String> contentmap = new HashMap<String ,String>();

	// HashMap<String, DetailFragment> fragments = new HashMap<String,
	// DetailFragment>();
	String							function_name;
	String							_id;
	String							cargo_criterion;
	int								criterion_type;

	public DetailActivity get_instance()
	{
		return this;
	}
	public void save_content(String which,String content)
	{
		contentmap.put(which, content);
		
	}
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		Log.d("DetailActivity", "onCreate");

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_detail);

		List<Fragment> fragments = getSupportFragmentManager().getFragments();
		if (fragments != null)
		{
			Log.d("DetailActivity", "fragments count=" + fragments.size());
//			for (int i = 0; i < fragments.size(); i++)
//				Log.e("DetailFragment", "fragment name="
//						+ fragments.get(i).getTag());

		}

		if (savedInstanceState != null)
		{
			tabmap = (LinkedHashMap<String, Integer>) savedInstanceState
					.getSerializable("tabmap");
			contentmap = (HashMap<String, String>) savedInstanceState.getSerializable("contentmap");
		}
		else
		{
			int count = getIntent().getIntExtra("actions_count", 0);
			for (int i = 0; i < count; i++)
			{
				int vid = commonUtil.generateViewId();
				tabmap.put(getIntent().getStringExtra("action" + i), vid);
			}
		}
		function_name = getIntent().getStringExtra("function_name");
		
		if(function_name.equals("Ocean Booking"))
			setTitle("Booking Detail");
		else if(function_name.equals("Ocean B/L info."))
			setTitle("B/L info. Detail");
		else if(function_name.equals("Container detail"))
			setTitle("Container Detail");
//		else if(function_name.equals("Cargo Tracking"))
//			setTitle("Cargo Detail");
//		
		
		if (function_name.equals("Cargo Tracking"))
		{
			criterion_type = getIntent().getIntExtra("criterion_type", 0);
			cargo_criterion = getIntent().getStringExtra("cargo_criterion");
		}
		_id = getIntent().getStringExtra("_id");
		setupTabs();

	}

	// @Override
	// protected void onSaveInstanceState(Bundle outState)
	// {
	// Iterator<String> iter=fragments.keySet().iterator();
	//
	// while (iter.hasNext())
	// {
	// String tag = (String) iter.next();
	// getSupportFragmentManager().putFragment(outState,tag,fragments.get(tag));
	//
	// }
	// outState.putStringArray("tags", fragments.keySet().toArray(new
	// String[0]));
	// Log.d("onSaveInstanceState","save fragments" +
	// fragments.keySet().size());
	// super.onSaveInstanceState(outState);
	// }
	//
	// @Override
	// protected void onRestoreInstanceState(Bundle savedInstanceState)
	// {
	// String [] tags =savedInstanceState.getStringArray("tags");
	// Log.d("onRestoreInstanceState","load fragments" + tags.length);
	// for(int i=0;i<tags.length;i++)
	// {
	// Log.d("onRestoreInstanceState","load fragment" + tags[i]);
	// fragments.put(tags[i],(DetailFragment)
	// getSupportFragmentManager().getFragment(savedInstanceState,tags[i]));
	// }
	//
	// super.onRestoreInstanceState(savedInstanceState);
	// }

	/** {@inheritDoc} */
	public View createTabContent(String tag)
	{
		FrameLayout fl = new FrameLayout(this);
		fl.setId(tabmap.get(tag));

		Fragment f;
		Bundle bundle = new Bundle();
		if (function_name.equals("Cargo Tracking"))
		{
			if (criterion_type == 0)
				bundle.putString("hbol", cargo_criterion);
			else
				bundle.putString("container_no", cargo_criterion);

		}
		bundle.putString("action_type", tag);
		bundle.putString("id", _id);
		bundle.putString("module_name", function_name);

//		Log.e("findFragmentByTag", "tag=" + tag + ", isnull= "
//				+ (getSupportFragmentManager().findFragmentByTag(tag) == null));

		f = getSupportFragmentManager().findFragmentById(tabmap.get(tag));
		if (f == null)
		{
			Log.d("createTabContent", "create fragment" + tag);
			f = new DetailFragment();

			
			f.setArguments(bundle);
		}
		((DetailFragment)f).set_content( contentmap.get(tag));
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.replace(fl.getId(), f);
		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		ft.addToBackStack(tag);
		ft.commit();
		return fl;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		outState.putSerializable("tabmap", tabmap);
		outState.putSerializable("contentmap", contentmap);
		super.onSaveInstanceState(outState);
	}

	// TabHost mTabHost;
	// private FrameLayout mTabContent;
	
//	@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 onKeyUp(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.onKeyUp(keyCode, event);
	}
	//
	// @Override
	// protected void onCreate(Bundle savedInstanceState)
	// {
	// super.onCreate(savedInstanceState);
	// setContentView(R.layout.activity_detail);
	// // Show the Up button in the action bar.
	// setupActionBar();
	// setupTabs();
	// }
	//
	// /**
	// * Set up the {@link android.app.ActionBar}.
	// */
	// private void setupActionBar()
	// {
	//
	// getActionBar().setDisplayHomeAsUpEnabled(true);
	//
	// }
	//
	// // private View createTabIndicatorView(ViewGroup parent, CharSequence
	// label, Drawable icon) {
	// // final LayoutInflater inflater = LayoutInflater.from(this);
	// // final View tabIndicator = inflater.inflate(R.layout.tab_indicator,
	// parent, false);
	// //
	// //// final TextView tv = (TextView)
	// tabIndicator.findViewById(R.id.tab_title);
	// //// tv.setText(label);
	// ////
	// //// final ImageView iconView = (ImageView)
	// tabIndicator.findViewById(R.id.tab_icon);
	// //// iconView.setImageDrawable(icon);
	// //
	// // return tabIndicator;
	// // }
	//
	// @Override
	// public View createTabContent(String tag)
	// {
	// final TextView tv = new TextView(this);
	// tv.setText("Content for tab with tag " + tag);
	// return tv;
	// }
	private void setupTabs()
	{
		mTabHost = (TabHost) findViewById(R.id.tabhost);
		// mTabContent = (FrameLayout) findViewById(android.R.id.tabcontent);
		// FrameLayout tab1 = new FrameLayout(this);
		mTabHost.setup();

		Iterator<String> iter = tabmap.keySet().iterator();
		while (iter.hasNext())
		{
			String name = (String) iter.next();
			mTabHost.addTab(mTabHost.newTabSpec(name).setIndicator(name)
					.setContent(this));
			// String val = (String) tabmap.get(field);
			// parms.putString(field, val);
			// // Cursor c = (Cursor) m_listadapter.getItem(key);
			// Log.d("@@@@@@@@@", field + " : " + val);
		}

		// for (int i=1; i <= tabmap.size(); i++) {
		// String name = tabmap.keySet().iterator().;
		// mTabHost.addTab(mTabHost.newTabSpec(name)
		// .setIndicator(name)
		// .setContent(this));
		// }
		// // if(true)
		// // return;
		//
		// // View tab1 = createTabIndicatorView(mTabHost.getTabWidget(),
		// // "Login",null);
		// // tabhost.addTab(
		// // tabhost.newTabSpec("tab" + i).setIndicator(tab)
		// // .setContent(Mytabfirst.this)); tabhost.setCurrentTab(i);
		// // i++; tab = null;
		//
		// // // ��ɵײ��Զ�����ʽ�İ�ť
		// // String[] title = new String[] { "Login", "Not login" };
		// // int[] tabIds = new int[] { R.id.tab1, R.id.tab2 };
		// mTabHost.addTab(mTabHost.newTabSpec("Login").setIndicator("Login")
		// .setContent(this));
		// //
		// mTabHost.addTab(mTabHost.newTabSpec("Direct Tracking").setIndicator("Direct Tracking").setContent(R.id.tab2));
		// mTabHost.addTab(mTabHost.newTabSpec("Service Location")
		// .setIndicator("Service Location").setContent(this));

		// FragmentManager manager = this.getFragmentManager();

		// Instantiate a new fragment.
		// Fragment loginFragment = new LoginFragment();
		// // Fragment dtFragement = new DirectTrackingFragment();
		// Fragment slFragment = new ServiceLocationFragment();
		// // Add the fragment to the activity, pushing this transaction
		// // on to the back stack.
		//
		// FragmentTransaction ft =
		// getSupportFragmentManager().beginTransaction();
		// ft.replace(mTabHost.getTabContentView().getChildAt(0).getId(),
		// loginFragment);
		// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		// ft.addToBackStack("Login");
		//
		// // ft.replace(R.id.tab2, dtFragement);
		// // ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		// // ft.addToBackStack("Tracking");
		//
		// ft.replace(R.id.tab3, (Fragment) slFragment);
		// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		// ft.addToBackStack("Location");
		//
		// ft.commit();

		// if (manager.findFragmentByTag(tabId) == null)
		// {
		// FragmentTransaction trans = manager.beginTransaction();
		// trans.replace(contentViewID, frag, tabId);
		// trans.commit();
		// }
		// for (int i = 0; i < title.length; i++) {
		// Button button = new Button(this);
		// button.setText(title[i]);
		// button.setBackgroundDrawable(this.getResources().getDrawable(
		// R.drawable.tab_lable)); //�Զ��尴ť��ʽ
		// mTabHost.addTab(mTabHost.newTabSpec(title[i]).setIndicator(button)
		// .setContent(tabIds[i]));
		// }

		// mTabHost.setOnTabChangedListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.action_addto_favorite:
//	            LayoutInflater factory = LayoutInflater.from(this);
//	            final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
	            final View edit = new EditText(this);
	             new AlertDialog.Builder(this)
	                .setIconAttribute(android.R.attr.alertDialogIcon)
	                .setTitle(R.string.str_createname)
	                .setView(edit)
	                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	String name = ((EditText)edit).getText().toString();
	                    	String param = getIntent().toUri(0);
	                    	
	        				SQLiteDatabase db = dbUtil.OpenDB(
	        						ApexTrackingApplication.get_instance(), null, true);
	        				db.execSQL("insert into favorites(name,params,user,create_time) values('"
	        						+ name
	        						+ "','"
	        						+ param
	        						+ "','"
	        						+ ApexTrackingApplication.get_user()
	        						+ "',"
	        						+ System.currentTimeMillis() + ")");
	        				dbUtil.CloseDB(db);                    	
	    
	                        /* User clicked OK so do some stuff */
	                    }
	                })
	                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {

	                        /* User clicked cancel so do some stuff */
	                    }
	                })
	                .create().show();
	             return true;


		}
		return super.onOptionsItemSelected(item);
	}

}
