package com.smart.gtstrvl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.commons.codec.binary.Base64;

import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.kind.GameCode;
import com.example.mountaintravel.service.BlueService;
import com.example.mountaintravel.util.PhoneUtil;
import com.example.mountaintravel.util.StringUtils;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.LoadingView;
import com.example.mountaintravel.view.TitleBarView;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.webkit.JavascriptInterface;

public class OriginalityActivity extends BaseActivity implements
		OnClickListener {
	private WebView originality_webview;
	private static final String TAG = "OriginalityActivity";
	private String url = "";
	private RelativeLayout originality_relative;
	private LoadingView virtual_loadingview;
	private SharedPreferences sp;
	private LinearLayout originality_layout;
	private Handler handler;
	private Context context;
	private String areaCode = "";
	private String code = "";
	private boolean talkEnd = false;
	private String sex = "1";
	private String gameUrl = "";
	private String branchUrl = "";
	private String continueUrlString;
	private int listId;
	private ArrayList<GameCode> list = new ArrayList<GameCode>();
	private boolean flag = true;
	private final static int SCANNIN_GREQUEST_CODE = 1;
	private boolean hasCode = false;
	private boolean hasPause = false;
	private BluetoothAdapter mBluetoothAdapter;
	protected String scanningId = "";
	protected String scanningAlt = "";

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_originality);
		initTitleBar("文创游");
		final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
		if (!mBluetoothAdapter.isEnabled()) {
			@SuppressWarnings("unused")
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			mBluetoothAdapter.enable(); // 强制开启蓝牙
			// mBluetoothAdapter.disable();
		}
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		originality_webview = (WebView) findViewById(R.id.originality_webview);
		originality_layout = (LinearLayout) findViewById(R.id.originality_layout);
		addview();
		WebSettings wSet = originality_webview.getSettings();
		wSet.setJavaScriptEnabled(true);
		originality_webview.getSettings().setCacheMode(
				WebSettings.LOAD_NO_CACHE);
		originality_webview.getSettings().setDomStorageEnabled(true);
		originality_webview.getSettings().setAppCacheEnabled(false);
		originality_webview.clearCache(true);
		originality_webview.addJavascriptInterface(new JsInteration(),
				"control");
		// url = "file:///android_asset/ori/gaotingshengci.html";
		if (sp.getString("sex", "").equals("女")) {
			sex = "0";
		}
		url = "http://" + Variable.address + "/terminal/game?userId="
				+ sp.getString("userid", "") + "&userName="
				+ sp.getString("nick_name", "") + "&sex=" + sex;
		// js弹出框弹出需要这句话
		originality_webview.setWebChromeClient(new WebChromeClient() {
		});
		originality_webview.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				if (!(url.contains("terminal/game?userId"))) {
					if (!mBluetoothAdapter.isEnabled()) {
						ToastUtil.show(OriginalityActivity.this, "请先开启蓝牙");
						return true;
					}
					if (!isWorked("com.example.mountaintravel.service.BlueService")) {
						BlueService.startSevice(OriginalityActivity.this);
					}
				}

				if (url.contains("terminal/game/branch/continue")) {
					talkEnd = true;
					return true;
				}
				if (url.contains("scene_no_exist")) {
					talkEnd = true;
				}
				if (url.contains("terminal/game/sponsor/scene/first/scanBarcode")) {
					scanningId = url.substring(url.indexOf("scanningId=") + 11,
							url.indexOf("scanningAlt"));
					int scanningAltId = StringUtils
							.indexOf(url, "scanningAlt=");
					scanningAlt = url.substring(scanningAltId + 12);
					if (!PhoneUtil.isCameraCanUse()) {
						if (VERSION.SDK_INT >= 23) {
							AlertDialog isExit = new AlertDialog.Builder(
									OriginalityActivity.this).create();
							isExit.setMessage("没有摄像头权限,去打开权限?");
							isExit.setButton("确定", listenerCrmera);
							isExit.setButton2("取消", listenerCrmera);
							isExit.show();
						} else {
							ToastUtil.show(OriginalityActivity.this, "无摄像头权限");
						}
					} else {
						Intent intent = new Intent();
						intent.setClass(OriginalityActivity.this,
								MipcaActivityCapture.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
					}

					return true;
				}

				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				flag = true;
				new Thread() {
					@Override
					public void run() {
						// super.run();
						int i = 0;
						while (flag) {
							i++;
							Log.d(TAG, i + "");
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (i > 60) {
								runOnUiThread(new Runnable() {
									public void run() {
										originality_webview
												.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});
							}
						}
					}
				}.start();
				originality_relative.setVisibility(View.VISIBLE);
				originality_webview.setVisibility(View.GONE);
				super.onPageStarted(view, url, favicon);
				Log.d(TAG, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				if (view.getUrl().contains("game_accept")) {
					String call = "javascript:getTask('android')";
					view.loadUrl(call);
				}
				flag = false;
				originality_webview.setVisibility(View.VISIBLE);
				originality_relative.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// TODO Auto-generated method stub
				super.onReceivedError(view, errorCode, description, failingUrl);
				flag = false;
				view.loadUrl("file:///android_asset/loading.html");
			}
		});
		originality_webview.loadUrl(url);
		context = getApplicationContext();
		// buleService.startSevice(OriginalityActivity.this);
		handler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (!talkEnd) {
					return;
				}
				if (hasCode) {
					return;
				}
				hasCode = true;
				code = (String) msg.obj;
				// Log.d(TAG, code + "SAD");
				if (list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						if (code.equals(list.get(i).getCode())) {
							if (list.get(i).getRoute().equals("main")) {
								talkEnd = false;
								url = "http://" + Variable.address
										+ continueUrlString;
								originality_webview.loadUrl(url);
							} else {
								talkEnd = false;
								url = "http://" + Variable.address
										+ list.get(i).getGameUrl();
								originality_webview.loadUrl(url);
							}
							listId = i;
						}
					}
					if (!talkEnd) {
						list.remove(listId);
					}
				}
				hasCode = false;

			}
		};

	}

	public class JsInteration {
		@JavascriptInterface
		public void toastMessage(String message) {
		}

		@JavascriptInterface
		public void onSumResult(String result) {
			continueUrlString = result;
			System.out.println(result);
			areaCode = result.substring(result.indexOf("areaCode=") + 9,
					result.indexOf("&areaBranchCodes"));
			// int urlId = StringUtils.indexOf(result, "game_accept?");
			// gameUrl = result.substring(urlId + 12);
			list.add(new GameCode("main", areaCode, continueUrlString));
			if (result.contains("areaBranchCodes")) {
				int branchId = StringUtils.indexOf(result, "areaBranchCodes=");
				String areaBranchCodes = result.substring(branchId + 16);
				String areaBranchCodeUrl = continueUrlString.replace("?",
						"/branch?");
				if (!areaBranchCodes.equals("")) {
					list.add(new GameCode("minor", areaBranchCodes,
							areaBranchCodeUrl));
				}
			}
			talkEnd = true;
		}
	}

	public void initTitleBar(String text) {
		TitleBarView v = (TitleBarView) findViewById(R.id.titleBarView1);
		if (v != null) {
			v.initTitleBar(R.drawable.zuoback, -1, text,
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							if (v.getId() == R.id.left_icon) {
								if (!(originality_webview.getUrl()
										.contains("terminal/game?userId"))) {
									AlertDialog isExit = new AlertDialog.Builder(
											OriginalityActivity.this).create();
									isExit.setMessage("确定要退出游戏吗?");
									isExit.setButton("确定", listener);
									isExit.setButton2("取消", listener);
									isExit.show();
								} else {
									finish();
								}
							}
						}
					});
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case SCANNIN_GREQUEST_CODE:
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				String result = bundle.getString("result");
				//http://gwms.517gts.com/terminal/game/family/

					byte[] outMsgBytes;
					try {
						outMsgBytes = result.getBytes("UTF-8");
						byte[] contentBytes = Base64.decodeBase64(outMsgBytes);
						String barcode = "http://gwms.517gts.com/terminal/game/family/"+new String(contentBytes, "UTF-8");
						originality_webview.loadUrl("javascript:appBackBarcode('"
								+ barcode + "','" + scanningId + "','" + scanningAlt
								+ "')");
					} catch (UnsupportedEncodingException e) { // TODO
						e.printStackTrace();
						ToastUtil.show(OriginalityActivity.this, "二维码有误");
					}
//				System.out.println(barcode + "                " + scanningId
//						+ "         " + scanningAlt);
//				originality_webview.loadUrl("javascript:appBackBarcode('"
//						+ barcode + "','" + scanningId + "','" + scanningAlt
//						+ "')");

			}
			break;
		case 10:
			if (PhoneUtil.isCameraCanUse()) {
				Intent intent = new Intent();
				intent.setClass(this, MipcaActivityCapture.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
			}
			break;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK
				&& !(originality_webview.getUrl()
						.contains("terminal/game?userId"))) {
			AlertDialog isExit = new AlertDialog.Builder(this).create();
			isExit.setMessage("确定要退出游戏吗?");
			isExit.setButton("确定", listener);
			isExit.setButton2("取消", listener);
			isExit.show();
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 创建退出对话框
			finish();
		}
		return false;
	}

	DialogInterface.OnClickListener listenerCrmera = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Uri packageURI = Uri.parse("package:" + "com.smart.gtstrvl");
				Intent intent = new Intent(
						Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
						packageURI);
				startActivityForResult(intent, 10);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};
	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				if (originality_webview.getUrl().contains("loading")) {
					finish();
				}
				url = "http://" + Variable.address + "/terminal/game?userId="
						+ sp.getString("userid", "") + "&userName="
						+ sp.getString("nick_name", "") + "&sex=" + sex;
				originality_webview.loadUrl(url);
				talkEnd = false;
				list.clear();
				list = null;
				list = new ArrayList<GameCode>();
				if (isWorked("com.example.mountaintravel.service.BlueService")) {
					Intent stopIntent = new Intent(OriginalityActivity.this,
							BlueService.class);
					stopService(stopIntent);
				}
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				break;
			}
		}
	};

	private boolean isWorked(String className) {
		ActivityManager myManager = (ActivityManager) OriginalityActivity.this
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
				.getRunningServices(300);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString()
					.equals(className)) {
				return true;
			}
		}
		return false;
	}

	public Handler getHandler() {
		return this.handler;
	}

	@SuppressLint("NewApi")
	public void addview() {
		WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics();
		display.getRealMetrics(outMetrics);
		originality_relative = (RelativeLayout) findViewById(R.id.originality_relative);
		virtual_loadingview = new LoadingView(getBaseContext(),
				outMetrics.widthPixels);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, 6);
		// lp.addRule(RelativeLayout.ALIGN_BASELINE);
		originality_relative.setOnClickListener(this);
		// lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
		originality_relative.addView(virtual_loadingview, lp);
	}

	public void onResume() {
		// TODO Auto-generated method stub
		if (!(originality_webview.getUrl().contains("terminal/game?userId"))) {
			if (hasPause
					&& !isWorked("com.example.mountaintravel.service.BlueService")) {
				BlueService.startSevice(OriginalityActivity.this);
			}
		}
		hasPause = false;
		virtual_loadingview.start();
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		if (isWorked("com.example.mountaintravel.service.BlueService")) {
			Intent stopIntent = new Intent(OriginalityActivity.this,
					BlueService.class);
			stopService(stopIntent);
		}
		hasPause = true;
		virtual_loadingview.stop();
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	}

	@SuppressLint("NewApi")
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		flag = false;
		if (isWorked("com.example.mountaintravel.service.BlueService")) {
			Intent stopIntent = new Intent(OriginalityActivity.this,
					BlueService.class);
			stopService(stopIntent);
		}
		if (originality_webview != null) {
			originality_layout.removeView(originality_webview);
			originality_webview.removeAllViews();
			originality_webview.onPause();
			originality_webview.destroy();
		}
	}

}
