package com.example.mountaintravel.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

import com.example.mountaintravel.adapter.Fragment5twoAdapter;
import com.example.mountaintravel.adapter.GamelistAdapter;
import com.example.mountaintravel.adapter.TeamListAdapter;
import com.example.mountaintravel.kind.TeamListInfo;
import com.example.mountaintravel.util.LoginUtil;
import com.example.mountaintravel.util.StringChangeUtils;
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 com.smart.gtstrvl.ApplyActivity;
import com.smart.gtstrvl.EventInfoActivity;
import com.smart.gtstrvl.GameListActivity;
import com.smart.gtstrvl.MainActivity;
import com.smart.gtstrvl.R;

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.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;

@SuppressLint({ "ValidFragment", "NewApi" })
public class ApplyFrag extends Fragment implements OnClickListener {
	private Context context;
	private RelativeLayout frag1_relative;
	private SharedPreferences sp;
	private LoadingView frag1_loadingview;
	private ListView listView;
	private TeamListAdapter adapter;
	private int positiontrue = 0;
	public ApplyFrag(Context context) {
		this.context = context;
	}

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

		return inflater.inflate(R.layout.fragment_1, 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
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
		setView();
		listView.setOnItemClickListener(listener);

		super.onActivityCreated(savedInstanceState);
	}

	android.widget.AdapterView.OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			positiontrue = position;
			AlertDialog isExit = new AlertDialog.Builder(context).create();
			// 设置对话框消息
			isExit.setMessage("确定要加入" + adapter.getItem(position).getTeamName()
					+ "吗？");
			// 添加选择按钮并注册监听
			isExit.setButton("确定", listeneradd);
			isExit.setButton2("取消", listeneradd);
			// 显示对话框
			isExit.show();
		}

	};

	@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();
		listView = (ListView) getView().findViewById(R.id.gamelist_lv);
		listView.setOnItemClickListener(listener);
		adapter = new TeamListAdapter(context);
		adapter.clear();
		frag1_relative.setVisibility(View.VISIBLE);
		listView.setVisibility(View.GONE);

		listView.setOnItemClickListener(listener);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				getTeamInfo();
			}
		}).start();
		// for (int i = 0; i < 5; i++) {
		// TeamListInfo info = new TeamListInfo(i + "A", i+"","加入团队");
		// adapter.addData(info);
		// }
		// listView.setAdapter(adapter);
		// adapter.notifyDataSetChanged();
	}

	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {

			case 0:
				ToastUtil.show(context, "加入团队成功");
				if (sp.getBoolean("apply", false)) {
					Intent intent = new Intent(context, GameListActivity.class);
					startActivity(intent);

				} else {
					Intent intent = new Intent(context, EventInfoActivity.class);
					startActivity(intent);
				}
				break;
			case 1:
				frag1_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				break;
			case 2:
				ToastUtil.show(context, "已有赛事团队");
				break;

			case 4:
				ToastUtil.show(context, "加入失败");
				break;
			case 5:
				frag1_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				Fragment5twoAdapter adapter5 = new Fragment5twoAdapter(context);
				adapter5.addData("暂无团队信息");
				listView.setAdapter(adapter5);
				adapter5.notifyDataSetChanged();
				ToastUtil.show(context, "网络异常，请检查网络");
				break;
			case 6:
				frag1_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				Fragment5twoAdapter adapter6 = new Fragment5twoAdapter(context);
				adapter6.addData("暂无团队信息");
				listView.setAdapter(adapter6);
				adapter6.notifyDataSetChanged();
				break;
			}

			super.handleMessage(msg);
		}
	};

	private void getTeamInfo() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String strURL = "http://" + Variable.address
				+ "/terminal/event/team_info_list";
		HttpPost httpPost = new HttpPost(strURL);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("eventId", ApplyActivity.eventId));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				String is = EntityUtils.toString(response.getEntity(), "UTF-8");
				// String result = StreamTools.streamToString(is);
				byte[] outMsgBytes = is.getBytes("UTF-8");
				String result = new String(outMsgBytes, "UTF-8");
				System.out.println(result);
				HashMap<String, Object> parameterMap = StringChangeUtils
						.toObject(result, HashMap.class);
				Object result_obj = parameterMap.get("teamList");
				List<String> AllUserInformation = (List<String>) result_obj;
				if (AllUserInformation.size() == 0) {
					Message message = new Message();
					message.what = 6;
					handler.sendMessage(message);
					return;
				}
				for (int i = 0; i < AllUserInformation.size(); i++) {
					HashMap<String, Object> userInfomation = StringChangeUtils
							.toObject(AllUserInformation.get(i), HashMap.class);
					String teamName = StringUtils.toString(userInfomation
							.get("teamName"));
					String teamNum = StringUtils.toString(userInfomation
							.get("teamNum"));
					String teamId = StringUtils.toString(userInfomation
							.get("teamId"));
					TeamListInfo info = new TeamListInfo(teamName, teamNum,
							teamId, "加入团队","");
					adapter.addData(info);
					// String repeaterSort =
					// StringUtils.toString(userInfomation.get("repeaterSort"));
					// String userId =
					// StringUtils.toString(userInfomation.get("axisX"));
				}
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			} else {
				Message message = new Message();
				message.what = 5;
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			Message message = new Message();
			message.what = 5;
			handler.sendMessage(message);
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	private void joinTeam() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String strURL = "http://" + Variable.address
				+ "/terminal/event/join_team";
		HttpPost httpPost = new HttpPost(strURL);
		
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("eventId", ApplyActivity.eventId));
			parameters.add(new BasicNameValuePair("userId", sp.getString(
					"userid", "")));
			parameters.add(new BasicNameValuePair("teamId", adapter.getItem(
					positiontrue).getTeamId()));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				String is = EntityUtils.toString(response.getEntity(), "UTF-8");
				// String result = StreamTools.streamToString(is);
				byte[] outMsgBytes = is.getBytes("UTF-8");
				String result = new String(outMsgBytes, "UTF-8");
				System.out.println(result);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				if (code.equals("000")) {
					Message message = new Message();
					message.what = 0;
					handler.sendMessage(message);

				} else if (code.equals("002")) {
					Message message = new Message();
					message.what = 2;
					handler.sendMessage(message);
				} else {
					Message message = new Message();
					message.what = 4;
					handler.sendMessage(message);
				}
			} else {
				Message message = new Message();
				message.what = 5;
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			Message message = new Message();
			message.what = 5;
			handler.sendMessage(message);
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	DialogInterface.OnClickListener listeneradd = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						joinTeam();
					}
				}).start();
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		listView.setOnItemClickListener(null);
	}

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

	}
}
