package com.smart.gtstrvl;

import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.LoadingView;

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.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

public class DeviceManaActivity extends BaseActivity implements OnClickListener {
	private WebView webView;
	private SharedPreferences sp;
	private String url;
	private ImageView device_ivback;
	private RelativeLayout MyDevice_relative;
	private LoadingView MyDevice_loadingview;
	LinearLayout device_layout;
	private ImageView device_ivadd;
	private static final String TAG = "DeviceManaActivity";
	private TextView device_tv;
	private boolean flag = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device_mana);
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		device_tv = (TextView) findViewById(R.id.device_tv);
		device_ivadd = (ImageView) findViewById(R.id.device_ivadd);
		addview();
		if (sp.getString("mydevice", "").equals("myBracelet")) {
			device_tv.setText("管理我的智能手表");
			sp.edit().putString("mydevice", "").commit();
			url = "http://" + Variable.address
					+ "/terminal/myBracelet?sesskey="
					+ sp.getString("sesskey", "");
			device_ivadd.setVisibility(View.GONE);
		} else {
			device_tv.setText("管理我的登山设备");
			url = "http://" + Variable.address + "/terminal/mydevice?sesskey="
					+ sp.getString("sesskey", "");
			device_ivadd.setVisibility(View.VISIBLE);
		}

		device_ivback = (ImageView) findViewById(R.id.device_ivback);
		device_ivadd = (ImageView) findViewById(R.id.device_ivadd);
		device_ivback.setOnClickListener(this);
		device_ivadd.setOnClickListener(this);
		webView = (WebView) findViewById(R.id.device_web);
		device_layout = (LinearLayout) findViewById(R.id.device_layout);
		WebSettings wSet = webView.getSettings();
		wSet.setJavaScriptEnabled(true);
		webView.getSettings().setDomStorageEnabled(false);
		webView.getSettings().setAppCacheEnabled(false);
		webView.loadUrl(url);
		webView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				
				MyDevice_loadingview.start();
				if (url.contains("deldevice=success")) {
					finish();
				}
				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() {
										webView.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});
								
							}

						}
					}

				}.start();
				MyDevice_relative.setVisibility(View.VISIBLE);
				webView.setVisibility(View.GONE);
				super.onPageStarted(view, url, favicon);
				Log.d(TAG, url);
			}
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// TODO Auto-generated method stub
				ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(DeviceManaActivity.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(DeviceManaActivity.this, "网络异常，请检查网络");
				} 
				super.onReceivedError(view, errorCode, description, failingUrl);
				flag=false;
				view.loadUrl("file:///android_asset/loading.html");

			}
			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				flag=false;
				MyDevice_loadingview.stop();
				webView.setVisibility(View.VISIBLE);
				MyDevice_relative.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}
		});
		
		webView.loadUrl(url);
	}
	public void onResume() {
		// TODO Auto-generated method stub
		MyDevice_loadingview.start();
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		MyDevice_loadingview.stop();
		super.onPause();
	}
	@SuppressLint("NewApi")
	public void addview() {
		WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics();
		display.getRealMetrics(outMetrics);

		MyDevice_relative = (RelativeLayout) findViewById(R.id.MyDevice_relative);
		MyDevice_loadingview = new LoadingView(getBaseContext(),
				outMetrics.widthPixels);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, 6);
		// lp.addRule(RelativeLayout.ALIGN_BASELINE);
		MyDevice_relative.setOnClickListener(this);
		// lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
		MyDevice_relative.addView(MyDevice_loadingview, lp);

	}

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

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.device_ivback:
			finish();
			break;
		case R.id.device_ivadd:
			Intent intent = new Intent(DeviceManaActivity.this,
					BindActivity.class);

			startActivityForResult(intent, 1);
			break;

		}

	}

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

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			webView.loadUrl(url);
			break;

		}
	}

}
