package com.example.mountaintravel.fragment;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import pl.droidsonroids.gif.GifImageView;

import com.example.mountaintravel.adapter.Fragment5twoAdapter;
import com.example.mountaintravel.adapter.GamelistAdapter;
import com.example.mountaintravel.kind.GameInfo;
import com.example.mountaintravel.util.AesTerminalUtil;
import com.example.mountaintravel.util.LoginUtil;
import com.example.mountaintravel.util.MD5Util;
import com.example.mountaintravel.util.StreamTools;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.LoadingView;
import com.smart.gtstrvl.BindActivity;
import com.smart.gtstrvl.DeviceManaActivity;
import com.smart.gtstrvl.GameListActivity;
import com.smart.gtstrvl.GameManagerActivity;
import com.smart.gtstrvl.LoginActivity;
import com.smart.gtstrvl.MainActivity;
import com.smart.gtstrvl.MyGradeActivity;
import com.smart.gtstrvl.PinfoActivity;
import com.smart.gtstrvl.R;
import com.smart.gtstrvl.VirtualRoadActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ProgressBar;

@SuppressLint({ "ValidFragment", "NewApi" })
public class WalkFragment extends Fragment implements OnClickListener {
	private Context context;
	private static final String TAG = "FragmentPage7";
	private RelativeLayout frag1_relative;
	private LoadingView frag1_loadingview;
	WebView frag6_web;
	String url = "";
	private SharedPreferences sp;
	private boolean flag = true;
	public WalkFragment(Context context) {
		this.context = context;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		return inflater.inflate(R.layout.fragment_6, container, false);
	}

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

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

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		setView();

		super.onActivityCreated(savedInstanceState);
	}

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

	}

	private void setView() {
		// TODO Auto-generated method stub
		addview();
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
		frag6_web = (WebView) getView().findViewById(R.id.frag6_web);
		WebSettings wSet = frag6_web.getSettings();
		wSet.setJavaScriptEnabled(true);
		frag1_relative.setVisibility(View.VISIBLE);
		frag6_web.setVisibility(View.GONE);
		frag6_web.getSettings().setAppCacheEnabled(false);

		url = "http://" + Variable.address
				+ "/terminal/bracelet_stepCount_report?sesskey="
				+ sp.getString("sesskey", "");

		// 设置 Application Caches 缓存目录
		frag6_web.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				frag1_loadingview.start();
				
				if (url.contains("error?err=13")) {
					AlertDialog isExit = new AlertDialog.Builder(context)
							.create();
					// 设置对话框标题
					isExit.setCancelable(false);
					// 设置对话框消息
					isExit.setMessage("暂无绑定手表，去绑定我的智能手表");
					// 添加选择按钮并注册监听
					isExit.setButton("确定", listener);
					isExit.setButton2("取消", listener);
					isExit.setCancelable(false);
					// 显示对话框
					isExit.show();
					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) {
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
								flag = false;
							}

						}
					}

				}.start();
				frag1_relative.setVisibility(View.VISIBLE);
				frag6_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
				ConnectivityManager cwjManager = (ConnectivityManager) context.getSystemService(context.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(context, "网络异常，请检查网络");
				} 
				flag = false;
				frag1_loadingview.stop();
				frag6_web.setVisibility(View.VISIBLE);
				frag1_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
				flag = false;
				view.loadUrl("file:///android_asset/loading.html");
				super.onReceivedError(view, errorCode, description, failingUrl);
			}
		});
		
		frag6_web.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress == 100) {
					
				} else {
					
				}
				super.onProgressChanged(view, newProgress);
			}
		});
		frag6_web.loadUrl(url);
	}
	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				frag6_web.loadUrl("file:///android_asset/loading.html");
				break;
			}

			super.handleMessage(msg);
		}
	};
	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Intent intent = new Intent(context, BindActivity.class);
				sp.edit().putString("adddevice", "addBracelet").commit();
				startActivityForResult(intent, 1);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				getActivity().finish();
				break;
			}
		}
	};

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

		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		flag=false;
		super.onDestroy();

	}

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

	}

}
