package com.example.hello.android.fragment_transaction_hello;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity
	implements View.OnClickListener
{

	private static final String LOG_TAG = "XXX";
	private static String HELLO_TAG = "HELLO";
	private static String GOODBYE_TAG = "GOODBYE";
	private static String GREETING_TAG = "GREETING";

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);

		Button helloButton = (Button) findViewById(R.id.hello_button);
		helloButton.setOnClickListener(this);
		Button goodbyeButton = (Button) findViewById(R.id.goodbye_button);
		goodbyeButton.setOnClickListener(this);

	}

	public void onClick(View view)
	{
		switch (view.getId())
		{
			case R.id.hello_button:
				showHelloFragment();
				break;
			case R.id.goodbye_button:
				showGoodbyeFragment();

				break;
			default:
		}
	}

	private void showHelloFragment()
	{
		Log.v(LOG_TAG, "showHelloFragment() : Hello");
		FragmentManager fragmentManager = getFragmentManager();

		Fragment helloFragment = fragmentManager.findFragmentByTag(HELLO_TAG);
		Log.v(LOG_TAG, "showHelloFragment() : helloFragment => " + helloFragment);
		if (helloFragment == null)
		{
			helloFragment = new HelloFragment();
		}

		FragmentTransaction ft = fragmentManager.beginTransaction();
		ft.replace(R.id.container, helloFragment, HELLO_TAG);
		ft.addToBackStack(GREETING_TAG);
		ft.commit();
		Log.v(LOG_TAG, "showHelloFragment() : Bye");
	}

	private void showGoodbyeFragment()
	{
		Log.v(LOG_TAG, "showHelloFragment() : Hello");
		FragmentManager fragmentManager = getFragmentManager();

		Fragment goodbyeFragment = fragmentManager.findFragmentByTag(GOODBYE_TAG);
		Log.v(LOG_TAG, "showHelloFragment() : goodbyeFragment => " + goodbyeFragment);
		if (goodbyeFragment == null)
		{
			goodbyeFragment = new GoodbyeFragment();
		}

		FragmentTransaction ft = fragmentManager.beginTransaction();
		ft.replace(R.id.container, goodbyeFragment, GOODBYE_TAG);
		ft.addToBackStack(GREETING_TAG);
		ft.commit();
		Log.v(LOG_TAG, "showHelloFragment() : Bye");
	}
}
