package com.smart.gtstrvl;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.EntityUtils;

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 android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
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.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.RelativeLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class PinfoActivity extends BaseActivity implements OnClickListener {
	private WebView pinfo_webview;
	private static final String TAG = "PinfoActivity";
	private String url = "";
	private RelativeLayout pinfo_relative;
	private LoadingView pinfo_loadingview;
	private SharedPreferences sp;
	LinearLayout pinfo_layout;
	private boolean flag = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pinfo);
		initTitleBar("基本信息");
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		pinfo_webview = (WebView) findViewById(R.id.pinfo_webview);
		pinfo_layout = (LinearLayout) findViewById(R.id.pinfo_layout);
		addview();
		WebSettings wSet = pinfo_webview.getSettings();
		wSet.setJavaScriptEnabled(true);
		pinfo_webview.getSettings().setDomStorageEnabled(false);
		pinfo_webview.getSettings().setAppCacheEnabled(false);
		url = "http://" + Variable.address + "/terminal/userinfo_index?userId="
				+ sp.getString("userid", "");
		// 设置 Application Caches 缓存目录
		pinfo_webview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				pinfo_loadingview.start();
				if (url.contains("userinfo_save/success")) {
					int a = StringUtils.indexOf(url, "nickName=");
					String nickName = url.substring(
							url.indexOf("nickName=") + 9, url.indexOf("&sex"));
					int sexId = StringUtils.indexOf(url, "sex=");
					String sex = url.substring(sexId + 4);
					if (sex.equals("0")) {
						sp.edit().putString("sex", "女").commit();
					}else{
						sp.edit().putString("sex", "男").commit();
					}
					byte[] outMsgBytes;
					try {
						outMsgBytes = nickName.getBytes("UTF-8");
						byte[] contentBytes = Base64.decodeBase64(outMsgBytes);
						String nick_name = new String(contentBytes, "UTF-8");
						sp.edit().putString("nick_name", nick_name).commit();
						if (sp.getBoolean("virtual", false)) {
							sp.edit().putBoolean("virtualPinfo", true).commit();
							finish();
						} else {
							startActivity(MainActivity.class);
						}

					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					return true;
				}
				view.loadUrl(url);

				return true;
			}
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// TODO Auto-generated method stub
				super.onReceivedError(view, errorCode, description, failingUrl);
				ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(PinfoActivity.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(PinfoActivity.this, "网络异常，请检查网络");
				} 
				flag=false;
				view.loadUrl("file:///android_asset/loading.html");

			}
			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				flag = false;
				pinfo_loadingview.stop();
				pinfo_webview.setVisibility(View.VISIBLE);
				pinfo_relative.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}
			@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() {
										pinfo_webview.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});
								
							}

						}
					}

				}.start();
				pinfo_relative.setVisibility(View.VISIBLE);
				pinfo_webview.setVisibility(View.GONE);
				super.onPageStarted(view, url, favicon);
				Log.d(TAG, url);
			}

		});

		
		pinfo_webview.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);

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

	}

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

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		pinfo_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;
		sp.edit().putBoolean("virtual", false).commit();
		if (pinfo_webview != null) {
			pinfo_layout.removeView(pinfo_webview);
			pinfo_webview.removeAllViews();
			pinfo_webview.onPause();
			pinfo_webview.destroy();
		}
	}
}
