package com.smart.gtstrvl;

import com.example.mountaintravel.base.BaseActivity;
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.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
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.Menu;
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;

public class TravelgradeActivity extends BaseActivity implements
		OnClickListener {
	private WebView travergrade_web;
	private SharedPreferences sp;
	private String url;
	LinearLayout travelgrade_layout;
	private RelativeLayout travergrade_relative;
	private LoadingView travergrade_loadingview;
	private static final String TAG = "TravelgradeActivity";
	private boolean flag = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_travelgrade);
		initTitleBar("赛事成绩");
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		url = "http://" + Variable.address + "/wap/event_list";
		travergrade_web = (WebView) findViewById(R.id.travergrade_web);
		travelgrade_layout = (LinearLayout) findViewById(R.id.travelgrade_layout);
		addview();
		WebSettings wSet = travergrade_web.getSettings();
		wSet.setJavaScriptEnabled(true);
		travergrade_web.getSettings().setDomStorageEnabled(false);
		travergrade_web.getSettings().setAppCacheEnabled(false);
		travergrade_web.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				travergrade_loadingview.start();
				if (url.contains("wap/event_repeater_ranking")) {
					int a = StringUtils.indexOf(url, "eventId=");
					String eventId = url.substring(a + 8);
					Intent intent = new Intent(TravelgradeActivity.this,
							MyGradeActivity.class);
					intent.putExtra("eventId", eventId);
					startActivity(intent);
					return true;
				}
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				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() {
										travergrade_web
												.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});

							}

						}
					}

				}.start();
				travergrade_relative.setVisibility(View.VISIBLE);
				travergrade_web.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
				flag = false;
				travergrade_loadingview.stop();
				travergrade_web.setVisibility(View.VISIBLE);
				travergrade_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
				ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(TravelgradeActivity.this.CONNECTIVITY_SERVICE);
				State mobile = cwjManager.getNetworkInfo(
						ConnectivityManager.TYPE_MOBILE).getState();
				State wifi = cwjManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
						.getState();
				if (!(mobile == State.CONNECTED || mobile == State.CONNECTING
						|| wifi == State.CONNECTED || wifi == State.CONNECTING)) {
					ToastUtil.show(TravelgradeActivity.this, "网络异常，请检查网络");
				} 
				super.onReceivedError(view, errorCode, description, failingUrl);
				flag = false;
				view.loadUrl("file:///android_asset/loading.html");
			}
		});
		
		travergrade_web.loadUrl(url);
	}

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

	}

	public void onResume() {
		// TODO Auto-generated method stub
		travergrade_loadingview.start();
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		travergrade_loadingview.stop();
		super.onPause();
	}

//	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) {
//							// TODO Auto-generated method stub
//							if (v.getId() == R.id.left_icon) {
//								if (travergrade_web.getUrl().contains("loading")) {
//									finish();
//									return ;
//								}
//								if (travergrade_web.canGoBack()) {
//									travergrade_web.goBack();
//								} else {
//									finish();
//								}
//							}
//						}
//					});
//		}
//	}

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

	@SuppressLint("NewApi")
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		flag = false;
		if (travergrade_web != null) {
			travelgrade_layout.removeView(travergrade_web);
			travergrade_web.removeAllViews();
			travergrade_web.onPause();
			travergrade_web.destroy();
		}
	}

//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (travergrade_web.getUrl().contains("loading")) {
//			finish();
//			return true;
//		}
//		if (keyCode == KeyEvent.KEYCODE_BACK && travergrade_web.canGoBack()) {
//			travergrade_web.goBack();// 返回前一个页面
//			return true;
//		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
//			finish();
//		}
//		return false;
//	}

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

	}

}
