package com.example.mountaintravel.fragment;

import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.LoadingView;
import com.smart.gtstrvl.BindActivity;
import com.smart.gtstrvl.EventInfoActivity;
import com.smart.gtstrvl.GameManagerActivity;
import com.smart.gtstrvl.MyGradeActivity;
import com.smart.gtstrvl.R;
import com.smart.gtstrvl.SportInfoActivity;
import com.smart.gtstrvl.TeamGradeActivity;

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.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.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

@SuppressLint({ "ValidFragment", "NewApi" })
public class GradeFragment extends Fragment implements OnClickListener {
	private Context context;
	private static final String TAG = "FragmentPage4";
	private RelativeLayout frag1_relative;
	private LoadingView frag1_loadingview;
	WebView frag4_web;
	String url = "";
	LinearLayout frag4_layout;
	private SharedPreferences sp;
	public static boolean flag = false;

	public GradeFragment(Context context) {
		this.context = context;
	}

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

		return inflater.inflate(R.layout.fragment_4, 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();
		frag4_layout = (LinearLayout) getView().findViewById(R.id.frag4_layout);
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
		frag4_web = (WebView) getView().findViewById(R.id.frag4_web);
		WebSettings wSet = frag4_web.getSettings();
		wSet.setJavaScriptEnabled(true);
		/*
		 * wSet.setSupportZoom(true); wSet.setBuiltInZoomControls(true);
		 */
		frag1_relative.setVisibility(View.VISIBLE);
		frag4_web.setVisibility(View.GONE);
		frag4_web.getSettings().setAppCacheEnabled(false);
		url = "http://" + Variable.address
				+ "/wap/event_repeater_ranking?eventId="
				+ GameManagerActivity.eventId + "&userId="
				+ sp.getString("userid", "-1");
		// 设置 Application Caches 缓存目录
		frag4_web.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				frag1_loadingview.start();
				if (url.contains("wap/event_team_user_repeater_ranking")) {
					Intent intent = new Intent(context, TeamGradeActivity.class);
					intent.putExtra("url", url);
					startActivity(intent);
					return true;
				}
				if (url.contains("wap/event_repeater_ranking_user_info")) {
					Intent intent = new Intent(context, SportInfoActivity.class);
					intent.putExtra("url", url);
					startActivity(intent);
					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);
				frag4_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;
				frag1_loadingview.stop();
				frag4_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
				super.onReceivedError(view, errorCode, description, failingUrl);
				flag = false;
				view.loadUrl("file:///android_asset/loading.html");

			}
		});

		frag4_web.loadUrl(url);

	}

	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				frag4_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;

			}
		}
	};

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		flag = false;
		super.onDestroy();
		if (frag4_web != null) {
			frag4_layout.removeView(frag4_web);
			frag4_web.removeAllViews();
			frag4_web.onPause();
			frag4_web.destroy();
		}
	}

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

	}
}
