package com.andengine.blackdog.chapter5;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andengine.blackdog.R;
import com.andengine.blackdog.chapter5.helper.BaseHelper;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class MainMenu extends BaseHelper {
	Intent intent = null;
	private EditText inputAddress = null;
	String text = null;
	String score;
	String money;
	String shuriken;

	// Admob
	Handler handler = new Handler();
	SharedPreferences pref = null;

	private void loadBannerView() {
		new Thread(new Runnable() {

			public void run() {
				handler.post(new Runnable() {

					public void run() {
						LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
						AdView adView = new AdView(MainMenu.this,
								AdSize.BANNER, "a151f1ddfe870c0");
						layout.addView(adView);
						AdRequest request = new AdRequest();
						adView.loadAd(request);
					}
				});
			}
		}).start();
	}

	void buyShuriken() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(R.drawable.icon)
				.setTitle("Buy Shuriken")
				// .setMessage("메인으로 돌아 가시겠습니까? 도중에 중단하면 기록이 저장되지 않습니다.")
				.setMessage(
						"Will You buy Shuriken with money?\n\n1 shuriken is 10 dollars.")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// 호출한다.
								// finish();
								money = pref.getString("money", "");
								Integer moneyInt = Integer.parseInt(money);
								Integer shurikenBuy = 0;
								shurikenBuy = moneyInt / 10;

								moneyInt = moneyInt - shurikenBuy * 10;

								shuriken = pref.getString("shuriken", "");
								Integer shurikenInt = 0;
								if (shuriken != "") {
									shurikenInt = Integer.parseInt(shuriken);
								}
								shurikenInt = shurikenInt + shurikenBuy;

								SharedPreferences pref = getSharedPreferences(
										"pref", Activity.MODE_PRIVATE); // UI
																		// 상태를
																		// 저장합니다.
								SharedPreferences.Editor editor = pref.edit(); // Editor를
																				// 불러
																				// 옵니다.

								editor.putString("shuriken",
										shurikenInt.toString());
								editor.putString("money", moneyInt.toString());

								editor.commit(); // 저장합니다.

								// -------------------------------------------
								// money
								// -------------------------------------------
								money = pref.getString("money", "");
								if (money.trim().length() != 0) {
									money = money + " Dollar";
								}
								TextView moneyTxt = (TextView) findViewById(R.id.money);
								moneyTxt.setText(money);

								// -------------------------------------------
								// 표창
								// -------------------------------------------
								shuriken = pref.getString("shuriken", "");
								if (shuriken.trim().length() == 0) {
									shuriken = "0";
								}
								TextView shurikenTxt = (TextView) findViewById(R.id.shurikenTxt);
								shurikenTxt.setText(shuriken);

							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
					}
				});
		builder.create().show();
	}

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.gc();

		setContentView(R.layout.main_menu);

		loadBannerView();

		// 이름 입력하기
		pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		inputAddress = (EditText) findViewById(R.id.inputAddr);

		// 저장된 값들을 불러옵니다.
		// 이름
		text = pref.getString("editText", "");
		inputAddress.setText(text);

		// 점수
		score = pref.getString("score", "");
		// 점수가 없을때는 표기 하지 않기 위해서
		if (score.trim().length() != 0) {
			score = score + " Meter";
		}
		TextView scoreTxt = (TextView) findViewById(R.id.score);
		scoreTxt.setText(score);

		// -------------------------------------------
		// money
		// -------------------------------------------
		money = pref.getString("money", "");
		if (money.trim().length() != 0) {
			money = money + " Dollar";
		}
		TextView moneyTxt = (TextView) findViewById(R.id.money);
		moneyTxt.setText(money);

		// -------------------------------------------
		// 표창
		// -------------------------------------------
		shuriken = pref.getString("shuriken", "");
		if (shuriken.trim().length() == 0) {
			shuriken = "0";
		}
		TextView shurikenTxt = (TextView) findViewById(R.id.shurikenTxt);
		shurikenTxt.setText(shuriken);

		// 게임시작 버튼
		findViewById(R.id.mark).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				intent = new Intent(getApplicationContext(), NinjaRun.class);
				startActivity(intent);
			}
		});

		// 기록 보기 버튼
		findViewById(R.id.book).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// todo:
				intent = new Intent(getApplicationContext(), WebForm.class);
				intent.putExtra("link", BaseHelper.URL + "rank_board_m.html");
				startActivity(intent);
			}
		});

		// 표창 사기 버튼
		findViewById(R.id.shuriken).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						buyShuriken();
					}
				});

	}

	private void clearApplicationCache(java.io.File dir) {
		if (dir == null)
			dir = getCacheDir();
		else
			;
		if (dir == null)
			return;
		else
			;
		java.io.File[] children = dir.listFiles();
		try {
			for (int i = 0; i < children.length; i++)
				if (children[i].isDirectory())
					clearApplicationCache(children[i]);
				else
					children[i].delete();
		} catch (Exception e) {
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		clearApplicationCache(null);
	}

	// 어플리케이션이 화면에서 사라질때 여러 값을 저장 합니다.
	@Override
	public void onStop() {
		super.onStop();
		SharedPreferences pref = getSharedPreferences("pref",
				Activity.MODE_PRIVATE); // UI 상태를 저장합니다.
		SharedPreferences.Editor editor = pref.edit(); // Editor를 불러 옵니다.

		inputAddress = (EditText) findViewById(R.id.inputAddr);
		editor.putString("editText", inputAddress.getText().toString());

		editor.commit(); // 저장합니다.

	}

	/*
	 * finish를 통해 다시 진입할 때는 onResume() 함수에 들어오게 됩니다.
	 */
	@Override
	public void onResume() {
		super.onResume();
		SharedPreferences pref = getSharedPreferences("pref",
				Activity.MODE_PRIVATE);
		// 점수
		score = pref.getString("score", "");
		// 점수가 없을때는 표기 하지 않기 위해서
		if (score.trim().length() != 0) {
			score = score + " Meter";
		}
		TextView scoreTxt = (TextView) findViewById(R.id.score);
		scoreTxt.setText(score);

		// -------------------------------------------
		// money
		// -------------------------------------------
		money = pref.getString("money", "");
		if (money.trim().length() != 0) {
			money = money + " Dollar";
		}
		TextView moneyTxt = (TextView) findViewById(R.id.money);
		moneyTxt.setText(money);

		// -------------------------------------------
		// shuriken
		// -------------------------------------------

		shuriken = pref.getString("shuriken", "");
		if (shuriken.trim().length() == 0) {
			shuriken = "0";
		}
		TextView shurikenTxt = (TextView) findViewById(R.id.shurikenTxt);
		shurikenTxt.setText(shuriken);
	}
}
